Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript and the DOM (Retiring) 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
231,270 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".