insertAdjacentHTML everywhere

Published on Updated on

If we want to insert content in a HTML document we have three ways to do it:

One can arguably say we also have document.write for few use cases.

innerHTML has been standardized in HTML5 and with it a brother method insertAdjacentHTML which works as innerHTML but allows us to define more specifically where we want to insert the HTML content: beforeBegin, afterBegin, beforeEnd and afterEnd.

var ul = document.getElementById("list");
ul.insertAdjacentHTML("beforeEnd", "<li>A new li on the list.</li>");

Back in 2008 John Resig wrote an article about insertAdjacentHTML with this conclusion:

Having browsers implement this method will dramatically reduce the amount of code needed to write a respectable JavaScript library. I'm looking forward to the day in which this method is more-widely available (along with querySelectorAll) so that we can really buckle down and do some serious code simplification.

Until now, the main issue with insertAdjacentHTML has been its lack of browser support. With Firefox implementing insertAdjacentHTML as of version 8, it will available in all major browsers including mobile browsers. If you want to use it now and make sure it works in Firefox versions earlier than 8 you can use this polyfill.

Last updated: Improve article

We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.