Why does innerHTML not work properly in the loop?

advertisements

What is the difference of this

var content= "";

for (i = 1; i <= 3; i++) {
    content = content + '<fieldset>' + '<legend>Grup ' + i + '</legend>';

    for (j = 1; j <= 5; j++) {
        content = content + '<div class="item"> item ' + i + ',' + j + '</div>';
    }

    content = content + '</fieldset>';
}

div.innerHTML = content;

and this

for (i = 1; i <= 3; i++) {
    div.innerHTML = div.innerHTML + '<fieldset>' + '<legend>Grup ' + i + '</legend>';

    for (j = 1; j <= 5; j++) {
        div.innerHTML = div.innerHTML + '<div class="item"> item ' + i + ',' + j + '</div>';
    }

    div.innerHTML = div.innerHTML + '</fieldset>';
}

I tried all the two ways. But the second one doesnt work as i expected. When i use div.innerHTML in for loop, the inner loop works after < /fieldset > and output is like :

<fieldset>
    <legend>Grup x</legend>
</fieldset>
<div class="item"> item 1,1 </div>
<div class="item"> item 1,2 </div>
....

You can test the issue at http://mutlakyazilim.com/test.html. Why are they different, anybody has idea ?


This is because innerHTML is a special property of HTML elements that has special behaviour when you get or set it.

When you get it (by doing var x = el.innerHTML for example), a serialization algorithm is run which converts the DOM sub-tree into HTML text.

When you set it (by doing el.innerHTML = el.innerHTML + '<html code>' for example), the text is sent through a html parser and set as the children if that element.


In your case, you are doing stuff like:

div.innerHTML = div.innerHTML + '<fieldset>';

Assuming div.innerHTML is initially empty, the code resolves to:

div.innerHTML = '<fieldset>';

this actually sends it through a parser, which generates html equivalent to:

<fieldset></fieldset>

which makes this code different.


A simple test you can run to confirm this is:

document.body.innerHTML = '<div>';
console.log(document.body.innerHTML); // should be `<div></div>`