Home > Back-end >  How to add 'space' between dynamically created elements?
How to add 'space' between dynamically created elements?

Time:09-29

As you can see there is spacing between the Label and Button via HTML, but when dynamically created via JS, there isn't. The CSS in the browser looks the same.

Html vs Js

It's because the HTML tags are on separate lines, creating a 'space' in between? If I put it on the same line it looks like the JS equivalent.

Now how to reproduce this in JS? A br element puts the button physically on a new line which is not what I want.

    const label = document.createElement("label");
    label.htmlFor  = `cash3`;
    label.textContent = `Week 3:`
    const delBtn = document.createElement("button");
    <label for="cash1">Week 1:</label>
    <button>Del</button>

CodePudding user response:

Try adding a margin-right property for label tag as common CSS, anyway, we need some margin-right for each label (say 5px right). so that you can avoid changing the JS code it will be inappropriate and you can able to create multiple dynamic from elements.

const label = document.createElement("label");
label.htmlFor  = `cash3`;
label.textContent = `Week 3:`
const delBtn = document.createElement("button");
delBtn.textContent = `Del`

document.querySelector('body').appendChild(label);
document.querySelector('body').appendChild(delBtn);

CSS:

label {
  margin-right: 5px;
}
// or
button {
  margin: 0 5px;    // margin on both left & right sides of button 
}

CodePudding user response:

'You can use &nbsp; to add a space in html' -
@Bladimir Medrano Vargas seems to be the answer

CodePudding user response:

Try this:

const label = document.createElement("label");
label.htmlFor = `cash3`;
label.textContent = `Week 3:`;

// adding style || play with margin
label.style.margin = "1rem";

const delBtn = document.createElement("button");
delBtn.innerText = "Button"

// where ever you can append the newly created elements
document.body.appendChild(label);
document.body.appendChild(delBtn);
  • Related