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 Challenge: Using nextElementSibling

Sean Flanagan
Sean Flanagan
33,235 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:

http://w.trhou.se/rvim5qeepw

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

Cheers

Sean

3 Answers

andren
andren
28,558 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,235 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; } });