Reusable function for insertAfter


Question about this function as seen in the book Javascript for Absolute Beginners:

This is the function:

funtion insertAfter (target, newElement) {
   target.parentNode.insertBefore(newElement, target.nextSibling) ;

My question: why is the second argument target.nextSibling and what does this mean? I thought it should be just target alone.


nextSibling is the next element in the current set of element children. So, for example,


Here we have a div and a bunch of elements inside (the children). The div is the parent, b is the firstChild, and i is b’s nextSibling. i’s nextSibling would be code. The last child, code, has no nextSibling since its at the end of the set of children.

What insertAfter does is inserts an element after another element. It does this by calling a different method, insertBefore. insertBefore inserts before another element. To make a before behave like an after, you call before on the next element in the set.

Lets say we’re inserting an img between b and i.


The “before” approach would be inserting it before i. The “after” approach would be inserting after b. So how insertAfter is written is using the “before” approach. However after is given a “target” of b, so in going with the before approach, we need to get to i from the b, and since its next to b (before the insertion occurs), its retrieved with target.nextSibling.


Thank you!