insertBefore are very useful when it comes to adding elements to a web page, but doing so often involves rather baroque navigation through the DOM, and laborious construction of elements.
Sometimes, you just want to sneak a tag and some content beside or inside an element. Thankfully,
insertAdjacentHTML can come to the rescue in those circumstances.
Targeting the Insert
A position parameter must be used with
insertAdjacentHTML, which may be one of four values:
afterend. It’s probably easiest to visualize these locations relative to a container element (although naturally
insertAdjacentHTML can be applied to any element):
If we imagine that that the element has an
#sidecontent, then the following code:
var sidecontent = document.getElementById("sidecontent"); sidecontent.insertAdjacentHTML("beforebegin", "<p>Day after day</p>");
…will place a paragraph containing the words “Day after day” before the
The following will place a heading at the start of the div:
var play = "<h1>Add It Up</h1>"; sidecontent.insertAdjacentHTML("afterbegin", play);
And this code at the end, after the last of the content that already exists in the element:
var butadd = "But the day after today"; sidecontent.insertAdjacentHTML("beforeend", butadd);
And finally, after the container:
var stoppage = "<p>I will stop</p>"; sidecontent.insertAdjacentHTML("afterend", stoppage);
Note that each of these takes a string, parsed into HTML, that is added to the DOM tree”.
insertAdjacentHTML doesn’t attempt to reinterpret the existing element on the page, and has no need to serialize the string it is supplied, so it executes much faster than methods such as
After all these procedures, our theoritical would look something like this:
Day after day
Add It Up
But the day after today
I will stop
So What’s The Difference?
What’s the difference between something like
appendChild must take built up, formed and created elements, while
insertAdjacentHTML takes a string with appropriate characters inside it.
Photograph by Visa Kopu, used under a Creative Commons Attribution-NoDerivs 2.0 Generic license
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.