JavaScript insertBefore() Method Tutorial

In this section, we will learn what the Element insertBefore() method is and how to use it in JavaScript.

What is Element insertBefore() Method in JavaScript?

The JavaScript Element insertBefore() method is used to insert an element as the child of another element.

Using this method gives us the ability to specify where exactly the new element should be placed between the other children of the target element.

JavaScript insertBefore() Method Syntax:

element.insertBefore(newElement, existingChildElement);

JavaScript insertBefore() Method Parameter

The method takes two arguments:

  • The first argument is a reference to the new element that we want to add as the child of the target element.
  • The second argument is a reference to a child element that we want to place the new element before that child.

JavaScript insertBefore() Method Return Value

The return value of this method is a reference to the same element that we’ve set as the first argument of the method.

Example: insertBefore() in JavaScript

See the Pen insertBefore() in JavaScript by Omid Dehghan (@odchan1) on CodePen.

JavaScript insertAfter

Using the insertBefore() method will insert a new element before another child of a target element. But what if we want to add an element “after” a child of the target element?

Well, in JavaScript there’s no method named `insertAfter()` I’m afraid! So it’s a bit of hacking to make an element appear as the child of another element, right next to one of its child!

To do this, we need a property named nextSibling. If you call this property on an element, it will return a reference to an element that sits next to the element that invoked this property.

So if for example, we want to add a new element after the first child of an element, we can get that first child, then call the nextSibling property on that first child to access the second child, and finally use the insertBefore() method to add the new element before the second child which is equal to after the first child.

It’s a bit complicated, so let’s run an example to see this in practice:

Example: insertAfter in JavaScript

See the Pen insertAfter in JavaScript by Omid Dehghan (@odchan1) on CodePen.


Top Technologies