Do innerHTML create nodes in a DOM tree?

If I do this:

document.getElementById("myDiv").innerHTML = "some_html_code"; 

will create nodes in my DOM three, as if I used appendChild() ?

The reason is because I am creating a mobile application where memory usage should be low. I do not want to create many nodes.

+4
source share
3 answers

This is about 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 through "html_string" you mean a string consisting of complex html, then, of course, nodes are created from html, if necessary (element nodes, comment nodes, text nodes, etc.). But a simple line of text is just one text node.

So, if your html line was '<div id="hello">world</div>' , it would be something like this:

 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); 

This is probably shocking how much happens with the simple, innocent .innerHTML installer, and it doesn't even include html syntax analysis.

It is important to note that none of this is garbage; all these created objects are necessary. To make sure that you create only the necessary nodes, do not use extra spaces between the nodes. for instance

 <span>hello</span> <span>world</span> 

are 3 text nodes, but

 <span>hello</span><span> world</span> 

- Only 2 text nodes.

Once upon a time, I created a fatal jsfiddle that converts html to "DOM code" for all these hateful .innerHTML haters.

+7
source

Yes, innerHTML will be processed and nodes will be created. There is no way, the DOM consists of nodes.

+4
source

It will create the string "a_html_string" and it will be displayed. but you can also add elements:

 document.getElementById("myDiv").innerHTML = "<a> Link </a>"; // will be displayed "Link" 
+1
source

All Articles