Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

Sean Flanagan
Sean Flanagan
33,231 Points

Using nextElementSibling: my solution

Hi my fellow coders.

I managed to create four Down buttons in my HTML file, but I can't make them work. When I click one, I get the above message.

The fault seems to be in Line 31 of my app.js. The conditional statement that covers lines 26-33 is supposed to fire the Down buttons.

Here's a snapshot:


I'd appreciate any advice on where I'm going wrong and how to rectify it.



3 Answers

28,499 Points

Despite the fact that there is a insertBefore method there is actually no method named insertAfter. That's why your code does not work.

But luckily there is actually a pretty easy way to insert an element after another by using the insertBefore method. Simply pass the arguments in the opposite order that you do when moving the element up.

Like this:

if (event.target.className == "down") {
    let li = event.target.parentNode;
    let nextLi = li.nextElementSibling;
    let ul = li.parentNode;
    ul.insertBefore(nextLi, li); // Specify the next element first, the current second.

If there is no next element (you are moving the last item) then you will pass null as the first argument which is actually fine, because the insertBefore method automatically places the second argument at the end of the container if null is passed as the first argument.

Sean Flanagan
Sean Flanagan
33,231 Points

Hi Andren.

That worked. I've given your reply an up vote and Best Answer.

Thank you.

Sean :-)

Óscar Hernández sandoval
Óscar Hernández sandoval
9,257 Points

Hey, took me the whole Sunday, but I did it here my code:

const list = document.getElementsByTagName('p')[0];

list.addEventListener('click', function(e) { if (e.target.tagName == 'BUTTON') { let p = list.nextElementSibling; } });