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

What and why do we use "ol.insertBefore(li, prevLi);" & "ol.insertBefore(nextLi, li);" for UP and DOWN button.??

What and why do we use "ol.insertBefore(li, prevLi);" & "ol.insertBefore(nextLi, li);" for UP and DOWN button.?? I couldnt get the concept. Can anyone explain in detail please..!

3 Answers

Steven Parker
Steven Parker
231,269 Points

In both cases, the code is changing the order of the items in the ordered list. The arguments specify the item that is being moved, and a reference item that it will be placed in front of.

In the second case, the intended result is to position the target item after another one, and since there is no "insertAfter" method, the arguments are simply reversed.

so it kinda goes like this parent.insertbefore ( item we want to be moved before , reference of item being moved before ); now in the up button i tried to swap the values of the up button to

if (event.target.className == 'up') {
      let li = event.target.parentNode;
      let prevLi = li.previousElementSibling;
      let ul = li.parentNode;
      ul.insertBefore(prevLi, li);
      }

now as prevli is the previous element sibling right so its like we are saying that insert previous list item before the list item. because li is the reference and prevLi is what we are moving before. but nothing happens, can you help me on this one . i think it should move up too but its not working so im wrong lol

I still dont understand the explanation. In both cases insertBefore changes items in the list. I 'UP' case change with element that is above (previousElementSibling) and id 'DOWN' case change it's place with item that is bottom (nextElementSibling). So why those 'li' element changes its places in insertBefore?

Steven Parker
Steven Parker
231,269 Points

Let me see if I can restate it. When you move up, you put the current item (li) before the the one that is above it (prevLi). So that explains "ol.insertBefore(li, prevLi)". But when you move down, you place the item that is below (nextLi) before the current one (li), so that's "ol.insertBefore(nextLi, li)".

In both cases, the arguments are given in the order they will appear after the move.

Thanks a lot, Steven, now It seems much more clear.