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

Using parentNode to Traverse Up the DOM

Instead of moving the event listener to the ul element from div element , what I did was "I assined a class of remove to every list-button" like this-

 <ul >
      <li>grapes <button class="remove">Remove</button></li>
      <li>amethyst <button class="remove">Remove</button></li>
      <li>lavender <button class="remove">Remove</button></li>
      <li>plums <button class="remove">Remove</button></li>
 </ul>

And then I put the condition-

if(event.target.className == "remove"){
            let listItem = event.target.parentNode;
            let parent = listItem.parentNode;
            parent.removeChild(listItem); 
        }               

But It didn't worked. Why this strange behaviour is going on?

2 Answers

tomd
tomd
14,685 Points

You need something to listen to the clicks on the buttons. You need addEventListener somewhere. Here are two ways of doing it:

First: Add event listeners to each li.

let li = document.querySelectorAll('li');

for(let lis of li) {
    lis.addEventListener('click', (event) => {
      if(event.target.className == "remove"){
        let ul = lis.parentNode;
        ul.removeChild(lis); 
      } 
    });
}

Second: Select the ul and listen for clicks inside it.

let ul = document.querySelector('.main-ul');

ul.addEventListener('click', (event) => {
  if(event.target.className == "remove"){
    let listItem = event.target.parentNode;
    let ul = listItem.parentNode;
    ul.removeChild(listItem); 
  } 
});

Hey @Tom Dempster
I have added "event-listener" to the "div" with class "list". I haven't removed that .
What i am saying is instead of moving the addEventListener closer , I just give "classes" to the element as the problem was I was selecting the button with tagname "button" , now I will select with className , so problem should be solved.

Hey @Aakash Srivastav, I think this is the solution you are looking for.

   const ul = document.querySelector('ul');

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