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.
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.
The return value of this method is a reference to the same element that we’ve set as the first argument of the method.
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?
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: