Search code examples
javascripthtml

Adding an input tag with js and dom appendChild seems to have no margin


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?


Solution

  • 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(false));
    .spaced { margin-right:5px; }