Solution 1 :

You can add the margin as follows:

let inp = document.createElement("input");
inp.style.margin='4px';
document.body.appendChild(inp);
inp = document.createElement("input");
inp.style.margin='4px';
document.body.appendChild(inp);

Solution 2 :

Add a whitespace or give a class with margins

// without
document.body.appendChild(document.createElement("input"));
document.body.appendChild(document.createElement("input"));

document.body.appendChild(document.createElement("hr"));

// with whitespace

document.body.appendChild(document.createElement("input"));
document.body.appendChild(document.createTextNode(" "));
document.body.appendChild(document.createElement("input"));

document.body.appendChild(document.createElement("hr"));

// with css
const input = document.createElement("input");
input.classList.add("spaced")
document.body.appendChild(input);
document.body.appendChild(input.cloneNode(1));
.spaced { margin-right:5px; }

Solution 3 :

The space between the input is not a margin, it’s propably a white a space, so when you add an element with js it’s appended without spaces, if you wrap the two inputs with a div with the style font-size: 0 you will see this space dissapear even for the inputs added in html

Problem :

When I add input tags with DOM appendChild() in a js script they seem to have no margin as they have no separation in between them. Input tags that have been written in the html file have that separation. The element inspector says they all have the same style.

The js script:

document.body.appendChild(document.createElement("input"));

I don’t know how to google this problem so I ask here, what’s going on and how can I fix this in the js script?

Comments

Comment posted by mplungjan

That is likely due to missing whitespace in the generated code

Comment posted by Diego

Works wonders, but I’d prefer not to mess with the style when it’s just a whitespace that’s missing in the html

By