javascripthtmlinnerhtml

Why does appending markup to innerHTML in pieces not behave the same as appending everything at once?


To better understand my problem here is a short example, I have following as my HTML,

var parent = document.getElementById("parent");

parent.innerHTML += "<ul>";
parent.innerHTML += "<li>Hello</li>";
parent.innerHTML += "</ul>";

console.log(parent.outerHTML);
<div id="parent"></div>

I'm expecting to receive output like

<div id="parent"><ul><li>Hello</li></ul></div>

But instead I am receiving below output,

<div id="parent"><ul></ul><li>Hello</li></div>

As you can see the <ul> tag is not enclosing the <li> tag. I know I can use appendChild for my problem but I'm really curious why this is happening. Any ideas?


Solution

  • The same result would happen if you left off your addition of </ul> entirely. The <ul> tag got closed when you did the first append to innerHTML to keep the code valid. If you assembled the string as a variable and appended it once, it would work:

    var tmp = "<ul>";
    tmp += "<li>Hello</li>";
    tmp += "</ul>";
    parent.innerHTML = tmp;