JavaScript insertAdjacentHTML and beforeend

By  on  

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.

This API wreaks of knowing a problem exists and fixing it -- who would have thought?!  OK, that was a bit passive aggressive but you know what I mean.  Keep insertAdjacentHTML handy -- it's a very lesser known API that more of us should be using!

Recent Features

  • By
    How I Stopped WordPress Comment Spam

    I love almost every part of being a tech blogger:  learning, preaching, bantering, researching.  The one part about blogging that I absolutely loathe:  dealing with SPAM comments.  For the past two years, my blog has registered 8,000+ SPAM comments per day.  PER DAY.  Bloating my database...

  • By
    How to Create a RetroPie on Raspberry Pi – Graphical Guide

    Today we get to play amazing games on our super powered game consoles, PCs, VR headsets, and even mobile devices.  While I enjoy playing new games these days, I do long for the retro gaming systems I had when I was a kid: the original Nintendo...

Incredible Demos

  • By
    Link Nudging with CSS3 Animations

    One of the more popular and simple effects I've featured on this blog over the past year has been linking nudging.  I've created this effect with three flavors of JavaScript:  MooTools, jQuery, and even the Dojo Toolkit.  Luckily CSS3 (almost) allows us to ditch...

  • By
    Introducing MooTools HeatMap

    It's often interesting to think about where on a given element, whether it be the page, an image, or a static DIV, your users are clicking.  With that curiosity in mind, I've created HeatMap: a MooTools class that allows you to detect, load, save, and...

Discussion

  1. DrifterZ28

    I have been using this for a while now and it has not failed me. Thanks for the nice quick tip to shed some light on this.

  2. MaxArt

    Avoiding .innerHTML += is basically the first thing I teach to Javascript novices when it comes to DOM manipulation.

    insertAdjacentHTML, although annoyingly verbose, is one of those handy methods that Microsoft introduced long ago, and that actually proved itself as a good idea.

    Now that even Firefox supports it (and since a while, to be fair), along with all the major mobile browsers, there’s no reason to not use it.

    • MaxArt

      Also, don’t forget some interesting options like "beforeBegin" and "afterEnd". They make the method work sort of like jQuery’s before and after, also filling the gap left by DocumentFraments for the task (which means: if you want to attach a bunch of HTML code after or before an element, you can’t use a DocumentFragment, because it doesn’t support innerHTML).
      Careful, though, because the element must have a parent (well, duh!) and older versions of IE give umpredictable results when it comes to special elements like or .

  3. I made a quick fork of someone’s jsperf benchmark and was surprised by the results – using the clunky DOM API is often faster than any of the HTML string APIs:

    http://jsperf.com/innerhtml-vs-insertadjacenthtml-vs-dom/8

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!