I have seen a few different methods to add elements to the DOM. The most prevelent seem to be, for example, either
document.getElementById('foo').innerHTML ='<p>Here is a brand new paragraph!</p>';
or
newElement = document.createElement('p');
elementText = document.createTextNode('Here is a brand new parahraph!');
newElement.appendChild(elementText);
document.getElementById('foo').appendChild(newElement);
but I’m not sure of the advantages to doing either one. Is there a rule of thumb as to when one should be done over the other, or is one of these just flat out wrong?
Some notes:
Using
innerHTMLis faster in IE, but slower in chrome + firefox. Here’s one benchmark showing this with a constantly varying set of<div>s +<p>s; here’s a benchmark showing this for a constant, simple<table>.On the other hand, the DOM methods are the traditional standard —
innerHTMLis standardized in HTML5 — and allow you to retain references to the newly created elements, so that you can modify them later.Because innerHTML is fast (enough), concise, and easy to use, it’s tempting to lean on it for every situation. But beware that using
innerHTMLdetaches all existing DOM nodes from the document. Here’s an example you can test on this page.First, let’s create a function that lets us test whether a node is on the page:
This will return
trueifparentcontainsdescendant. Test it like this:This will print:
It may not look like our use of
innerHTMLshould have affected our reference to theportalLinkelement, but it does. It needs to be retrieved again for proper use.