Append an element to the DOM as nth child using insertBefore

OpenJavaScript 0
Reading Time: 2 minutes 🕑

Last updated: March 24, 2022.

Sometimes, you may come across a situation where you want to use JavaScript to append an element to the DOM as a middle child.

For example, in the following HTML code, there are six paragraphs contained within the <div id = "article-body"> element:

    <article id="article">
        <h1 id="title">Content</h1>
        <div id="article-body">
            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
            <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
        </div>
    </article>

Let’s say we want to insert an image before the fourth paragraph.

insertBefore

For this, we can apply the insertBefore method to the parent element. We then specify the element we want to insert to the DOM as a first argument; and as a second argument, the element it should be inserted before:

parentElement.insertBefore(newElement, existingElement)

Applied to the example above, we can insert an image before the fourth paragraph as follows:

// Create an element to be inserted
const img = document.createElement('img');
img.src = "http://unsplash.it/600/100";

// Select parent element and element to insert new element before
articleBody = document.getElementById('article-body');
para = articleBody.querySelectorAll('p')[3];

// Apply insertBefore to parent, specify new element as first argument the second as the one to insert before
articleBody.insertBefore(img, para);
// Result: inserts before paragraph four
Using insertBefore in JavaScript: First example

Inventing an insertAfter

Unfortunately, an insertAfter method is not supported. But if you do want to insert a new element after an existing element, it is possible with a minor workaround: apply the nextSibling method when selecting amongst the children of the parent. Then, when insertBefore is used, it will the new element after the element to which nextSibling was applied:

// Create an element to be inserted
const img = document.createElement('img');
img.src = "http://unsplash.it/600/100";

// Select parent element and element to insert new element after and apply nextSibling
articleBody = document.getElementById('article-body');
para = articleBody.querySelectorAll('p')[3].nextSibling;

// Apply insertBefore to parent, specify new element as first argument the second as the one to insert after
articleBody.insertBefore(img, para);
// Result: inserts after paragraph four
Using insertBefore in JavaScript: Second example

Don't forget about append and prepend

Bear in mind that insertBefore is not necessary if you want to insert an element as the first or last child: for this, just apply prepend (first child) or append (last child) to the parent, passing in the new element:

// Create an element to be inserted
const img = document.createElement('img');
img.src = "http://unsplash.it/600/100";

// Select parent element
articleBody = document.getElementById('article-body');

// Apply prepend or append to insert new element as first or last child:
articleBody.prepend(img);
// Result: image is inserted as first child