HTML DOM createElement in for loop

when i want to add child to html with Dom i want to insert some files into it but i am confused about for loop. The first time I try this:

<div id="whitespaces"></div>
<script type="text/javascript">
window.onload = function() {
    var br = document.createElment("br")
    var wh = document.getElementById("whitespaces");
    for (var count = 1; count < 11; count++){
        wh.appendChild(br);
    }
}
</script>

      

And I only get 1 <br> in the html.

Then I'll try:
        window.onload = function () {

    var wh = document.getElementById("whitespaces");
    for (var count = 1; count < 11; count++){
        wh.appendChild(document.createElement("br"));
    }
}
</script>

      

In this I get 10 <br> in my html page. So why is result 2 different? Is br variable not equal to document.createElment ("br")?

+3


source to share


1 answer


Because it br

is a unique element. When you use appendChild

it removes the element from where it was and inserts it somewhere else. In addition to creating a new node every time, like in your second example, what you can do is clone the node:



var br = document.createElment("br")
var wh = document.getElementById("whitespaces");
for (var count = 1; count < 11; count++){
    wh.appendChild(br.cloneNode());
}

      

+3


source







All Articles