JavaScript insertAdjacentHTML and beforeend

In case you didn't know: the damn DOM is slow. As we make our websites more dynamic and AJAX-based, we need to find ways of manipulating the DOM with as little impact on performance as possible. A while back I mentioned DocumentFragments, a clever way of collecting child elements under a "pseudo-element" so that you could mass-inject them into a parent. Another great element method is insertAdjacentHTML : a way to inject HTML into an element without affecting any elements within the parent.

The JavaScript

If you have a chunk of HTML in string format, returned from an AJAX request (for example), the common way of adding those elements to a parent is via innerHTML:

function onSuccess(newHtml) { parentNode.innerHTML += newHtml; }

The problem with the above is that any references to child elements or events connected to them are destroyed due to setting the innerHTML, even if you're only appending more HTML -- insertAdjacentHTML and beforeend fixes that issue:

function onSuccess(newHtml) { parentList.insertAdjacentHTML('beforeend', newHtml); }

With the code sample above, the string of HTML is appended to the parent without affecting other elements under the same parent. It's an ingenious way of injecting HTML into a parent node without the dance of appending HTML or temporarily creating a parent node and placing the child HTML within it.