JavaScript JavaScript and the DOM Traversing the DOM Using parentNode to Traverse Up the DOM

anthonybrackner
anthonybrackner
17,776 Points

Code Not Working

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

listUl.addEventListener('click', (event) => { if (event.target.tagName == 'BUTTON') { let li = event.target.parentNode; let ul = li.parentNode; ul.removeChild(li); } });

The above code is not working and I have no idea why. It appears to be what Guil is coding himself. What a frustrating module.

4 Answers

Andreas Nyström
Andreas Nyström
8,849 Points

Hi Anthony.

From what I can see your code looks correct, but that is out of context. When asking questions try using the Markdown for what you're trying to show. See more here: https://teamtreehouse.com/community/howto-guide-markdown-within-posts.

Also I think we need to see the rest of the code to help you here.

So maybe you can snapshot your workspace and paste it here? To do this:

  1. You go to your workspace and click the thirt button from the right on the top-right corner. (It looks like a camera).
  2. Share the link here (like this one! https://w.trhou.se/3c329u10z1)

Or you could paste all the code in here, but it's simpler for us if you just snapshot it if its a lot of code :).

Andreas Nyström
Andreas Nyström
8,849 Points

Hi again Anthony.

Your code that you displayed here was correct. However, on line 25:

toggleList.addEventListener('click', function() {
  if (listDiv.style.display == 'none') {
    toggleList.textContent = 'Hide list';
    listDiv.style.display = 'block';
  } else {
    toggleList.textContent = 'Show list';
    listDiv.style.display = 'none';
   }

You forgot to end your eventlistener. So the code on line 25 should be:

toggleList.addEventListener('click', function() {
  if (listDiv.style.display == 'none') {
    toggleList.textContent = 'Hide list';
    listDiv.style.display = 'block';
  } else {
    toggleList.textContent = 'Show list';
    listDiv.style.display = 'none';
   }
});

I think this is all you need to do. If you're having trouble with the code sometime, try bringing up the console in your browser. See how here: https://kb.mailster.co/how-can-i-open-the-browsers-console/

There is often an explanation on why it's not working and then you can see where and what the bug is.

Hope this helps, keep at it and happy coding!

anthonybrackner
anthonybrackner
17,776 Points

Thanks so much Andreas! I was looking at every part of the code except for that section.