It is roughly the same as
var div = document.getElementById("myDiv");
while( div.firstChild ) {
div.removeChild( div.firstChild );
}
div.appendChild( document.createTextNode("a_html_string") );
Of course, if by "html_string"
you mean a string consisting of complex html, then of course nodes are created from the html as appropriate (element nodes, comment nodes, text nodes etc). But a simple string of text is simply a single text node.
So if your html string were '<div id="hello">world</div>'
, that would roughly be:
var div = document.getElementById("myDiv");
while( div.firstChild ) {
div.removeChild( div.firstChild );
}
var anotherDiv = document.createElement("div");
anotherDiv.setAttribute("id", "hello");
anotherDiv.appendChild(document.createTextNode("world"));
div.appendChild(anotherDiv);
It is probably shocking how much is happening with a simple innocent looking .innerHTML
setter, and this is not even including parsing the html.
It's important to note that none of this is garbage, all of those objects created are necessary. To make sure you are only creating necessary nodes, do not use unnecessary whitespace between nodes. For example
<span>hello</span> <span>world</span>
is 3 text nodes but
<span>hello</span><span> world</span>
is only 2 text nodes.
A long while ago I created a facetious jsfiddle that converts html to "DOM code" for all of those .innerHTML haters.