JavaScript JavaScript and the DOM Traversing the DOM Solution: Using nextElementSibling

Brandon Marrero
Brandon Marrero
5,532 Points

my solution using insertAfter()

There is no mehtod called insertAfter() so I created on:

function insertAfter(element, referenceNode) { referenceNode.parentNode.insertBefore(element, referenceNode.nextElementSibling); }

Then in the if(nextLi) statement call the function:

if (nextLi) { insertAfter(li, nextLi); }

1 Answer

Steven Parker
Steven Parker
182,465 Points

The next node might not be an element, so you probably want to use just "nextSibling". Then, you can simplify by adding it to the "Node" prototype directly, making it a new method:

Node.prototype.insertAfter = function(newNode, referenceNode) {
  return this.insertBefore(newNode, referenceNode.nextSibling);

This will allow it to be called exactly like you might use "insertBefore".