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

Samantha Atkinson
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Samantha Atkinson
Front End Web Development Techdegree Graduate 40,307 Points

Which li item is actually moving? Is it the one next to the button you click?

When you create variables for:

let prevLi = li.previousElementSibling;
let nextLi = li.nextElementSibling;
<ul>
<li>amethyst 
          <button class="up">Up</button> 
          <button class="down">Down</button>             
          <button class="remove">Remove</button>
        </li>
        <li>lavender 
          <button class="up">Up</button>
          <button class="down">Down</button>              
          <button class="remove">Remove</button>
        </li>
        <li>plums 
          <button class="up">Up</button> 
          <button class="down">Down</button>             
          <button class="remove">Remove</button>
        </li>
      </ul>

So if I click the Down button on the amenthyst is it the li item lavender that is the actual element that moves because it's the nextElementSibling ?

1 Answer

Steven Parker
Steven Parker
231,261 Points

You're exactly right. The move is performed by this line:

    ul.insertBefore(nextli, li);

So it's the next list item that gets moved, and placed in front of the one containing the button that was clicked.

Samantha Atkinson
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Samantha Atkinson
Front End Web Development Techdegree Graduate 40,307 Points

Thank you, Steven, that clarifies my understanding of the nextElementSibling or previousElementSibling. I really didn't get it the first time. I am going to have a look over the code again with new understanding eyes : )