Sitemap

insertAdjacentElement in JavaScript

2 min readNov 14, 2022

As software developers, we traditionally take our first steps into DOM manipulation utilizing the append or appendChild methods. These methods allow us to dynamically add content to the bottom of an element on the webpage — Church! But what if we need to add content not at the bottom?

Consider append syntax:

const main = document.querySelector('div');
const h1 = document.querySelector('h1');//h1 is already inside the main
const content = document.createElement('p');
main.append(content);

In this example, our content is going to be added after h1 because h1 is already inside the main div element.

Get Nathan F.’s stories in your inbox

Join Medium for free to get updates from this writer.

Now what if there was already an h2 element after the h1, but we still want to add our content directly after h1?(Between h1 and h2)

Here is the juicy insertAdjacentElement solution:

const main = document.querySelector('div');
//h1 and h2 are already inside the main div
const h1 = document.querySelector('h1');
const h2 = document.querySelector('h2');

const content = document.createElement('p');
h1.insertAdjacentElement("afterend", content);

The result of our solution would sandwich our content between the h1 and h2 elements. We said, “Hey content, look at h1. Go after the end of h1.” Notice that the location has to be in quotes.

We can also send content to locations: beforebegin, afterbegin, beforeend, and back to afterend.

Be aware that if we use locations “afterbegin” or “beforeend”, the content will be placed inside of the element. In other words, if we put content “afterbegin” on the h1, the content will be placed before whatever text is already inside the h1. ex: “Hello World” => “content Hello World”