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

Siddharth Pandey
Siddharth Pandey
4,069 Points

Why doesn't this work, someone please explain?

How come for the add next list item challenge this code does not work, what is wrong with it, I'm really struggling to understand:

const downButton = listDiv.querySelector('button.down');

downButton.addEventListener('click', function down(event) { let li = event.target.parentNode; let ul = li.parentNode; let nextLi = li.nextElementSibling; ul.insertBefore(li, nextLi);
});

1 Answer

Jonathan Grieve
MOD
Jonathan Grieve
Treehouse Moderator 83,234 Points

Hi Siddarth,

If nothing is happening when you click a button or take any action it means the code has thrown an error. Which you'll be able to check out when you look at the JavaScript console.

You can do this via your browser's development tools. In Chrome Dev Tools for example. Does the console tab tell you anything?

I think one problem might be you want to call querySelector on document and not listDiv but it's hard to call without looking at more of your code. Good luck! :-)

Siddharth Pandey
Siddharth Pandey
4,069 Points

The console show's no errors, and here's the HTML of my code:

<!DOCTYPE html> <html> <head> <title>JavaScript and the DOM</title> <link rel="stylesheet" href="css/style.css"> </head> <body> <h1 id="myHeading">JavaScript and the DOM</h1> <p>Making a web page interactive</p> <button id="toggleList">Hide list</button> <div class="list"> <p class="description">Things that are purple:</p> <input type="text" class="description"> <button class="description">Change list description</button> <ul> <li> grapes <button class="down">Down</button> </li> <li> amethyst <button class="down">Down</button> </li> <li> lavender <button class="down">Down</button> </li> <li> plums <button class="down">Down</button> </li> </ul> <input type="text" class="addItemInput"> <button class="addItemButton">Add item</button> <button class="removeItemButton">Remove last item</button> </div> <script src="app.js"></script> <script src="temp.js"></script> </body> </html>

Here's the listDiv variable:

const listDiv = document.querySelector('.list');

The console shows no errors, and only the grapes list item moves down.

Jonathan Grieve
Jonathan Grieve
Treehouse Moderator 83,234 Points

try using document.querySelectorAll(). querySelector will only match the first instance. Again it's hard to test from this end even with the code but I believe that should work. :-)

Siddharth Pandey
Siddharth Pandey
4,069 Points

Thanks for your help so far, but when I use querySelectorAll() it still does not work, I get the syntax error "Uncaught TypeError: downButton.addEventListener is not a function". Do you have any other suggestions, and can you please explain why I would get such a syntax error. Thanks for helping :-)