Skip to main content
Home

insertAdjacent* family of DOM methods

This is more of an appreciation post for how useful the insertAdjacent* family of helpers is as opposed to doing a full coverage on them.

To be specific, these are the methods, in the order of usage occurences in my day to day tasks:

All of these accept a special position descriptor as their 1st argument and a string or a node of Element type as the content that needs to be inserted in the desired place.

Possible values for position here are pretty self explanatory but for some reason I have to look them up anyway when I have to use the method:

<!-- beforebegin -->
<div>
  <!-- afterbegin -->

  <!-- beforeend -->
</div>
<!-- afterend -->

Maybe it's time to think of a good mnemonic for them?

Anyways, I just appreciate how concise and obvious the code that uses these helpers is, it just gets the job done in such an easy manner.

document
  .querySelector('#header')
  .insertAdjacentHTML('beforebegin', '<div>Some very important ad.</div>');

Raw and imperative DOM manipulation isn't everyone's piece of cake for sure, but finding such gems in the browser APIs makes the whole process less of a hassle for me personally.

Profile picture

Andrei Glingeanu's notes and thoughts. You should follow him on Twitter, Instagram or contact via email. The stuff he loves to read can be found here on this site or on goodreads. Wanna vent or buy me a coffee?