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

James Nguyen
PRO
James Nguyen
Pro Student 3,306 Points

this video is something wrong because of nextLi= li.nextElementSibling then ul.insertBefore(nextLi,li) is the same. so

so it is the same. I think we should use afterNextLi = nextLi.nextElementSibling then ul.insertBefore(afterNextLi, li) that will make sense

2 Answers

Owen Bell
Owen Bell
7,720 Points

I think you're a bit confused as to how the .insertBefore method works. Check the MDN documentation for more clarification. You should see the following syntax template:

var insertedNode = parentNode.insertBefore(newNode, referenceNode);

The first parameter of .insertBefore specifies the element to be moved; the second specifies the element that the first is to be inserted before.

Guil's code selects the list item whose 'Down' button was clicked and stores it in the li variable, then selects the next list item (if it exists) and stores that in the nextLi variable (undefined if no next item exists). Finally, he selects the entire list and stores it in ul. The conditional statement then checks if nextLi is truthy; in other words, does a next list element exist, or is the element stored in li the final list item? If there is a next item, the following code block runs:

ul.insertBefore(nextLi, li);

This removes the next list element from its current position and inserts it before the list item whose 'Down' button was clicked - the result of this is that the next list item moves upwards whilst the clicked item moves downwards.

James Nguyen
PRO
James Nguyen
Pro Student 3,306 Points

thank you verry much I am sorry about that