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
    Send Text Messages with PHP

    Kids these days, I tell ya.  All they care about is the technology.  The video games.  The bottled water.  Oh, and the texting, always the texting.  Back in my day, all we had was...OK, I had all of these things too.  But I still don't get...

  • By
    CSS 3D Folding Animation

    Google Plus provides loads of inspiration for front-end developers, especially when it comes to the CSS and JavaScript wonders they create. Last year I duplicated their incredible PhotoStack effect with both MooTools and pure CSS; this time I'm going to duplicate...

Incredible Demos

  • By
    Create a Simple Slideshow Using MooTools

    One excellent way to add dynamism to any website is to implement a slideshow featuring images or sliding content. Of course there are numerous slideshow plugins available but many of them can be overkill if you want to do simple slideshow without controls or events.

  • By
    Create a CSS Cube

    CSS cubes really showcase what CSS has become over the years, evolving from simple color and dimension directives to a language capable of creating deep, creative visuals.  Add animation and you've got something really neat.  Unfortunately each CSS cube tutorial I've read is a bit...

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!