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

What is the point of "if (nextLi)"?

I did it without the extra if statement, and my code worked just fine.

    if (e.target.className == 'move-down') {
      let li = e.target.parentNode;  
      let nextLi = li.nextElementSibling;
      let ul = li.parentNode;
      ul.insertBefore(nextLi, li);
    }

Even when you click the "down" button next to the final list item, it doesn't move, as expected.

1 Answer

Steven Parker
Steven Parker
171,958 Points

Without it your script will be causing errors.

Obviously, the final item cannot move down, because there's no lower spot to go to. But by removing the test, your code will attempt to move it and will fail and cause errors.

Try opening the console in your browser's developer tools and watch while you click the down button.

There may be no behavioral difference in your current browser, but a different one (or a future version) might permanently deactivate an event handler that causes errors.

ywang04
ywang04
6,733 Points

You're right. :) Below is the error without if statement.

app.js:30 Uncaught TypeError: Failed to execute 'insertBefore' on 'Node': parameter 1 is not of type 'Node'.
    at HTMLUListElement.listUl.addEventListener (app.js:30)