Search code examples
javascriptarraylisthtmlcollection

How would I remove each Item after clicking the button next to it using plain Java script


Below is the html code

 <ul>
        <li>Item 1<button class="btn">click</button></li>
        <li>Item 2<button class="btn">click</button></li>
        <li>Item 3<button class="btn">click</button></li>
        <li>Item 4<button class="btn">click</button></li>
        <li>Item 5<button class="btn">click</button></li>
 </ul>

Below is JS code

var ul=document.querySelector("ul");
var li= document.querySelector("li");
var button= document.querySelectorAll(".btn");

button.forEach(function(i){
    i.onclick=function(){
        ul.removeChild(li);
    }
})

and the above code only removes the first item. I really do not know how to implement this one. Really confused on the html collections and node list concept.


Solution

  • Inside the handler, select the button's parentElement and remove() it:

    var button = document.querySelectorAll(".btn");
    
    button.forEach(function(button) {
      button.onclick = function() {
        button.parentElement.remove();
      }
    })
    <ul>
      <li>Item 1<button class="btn">click</button></li>
      <li>Item 2<button class="btn">click</button></li>
      <li>Item 3<button class="btn">click</button></li>
      <li>Item 4<button class="btn">click</button></li>
      <li>Item 5<button class="btn">click</button></li>
    </ul>

    You could also use event delegation instead, if you wanted, rather than adding multiple listeners:

    document.querySelector('ul').addEventListener('click', ({ target }) => {
      if (target.className === 'btn') {
        target.parentElement.remove();
      }
    });
    <ul>
      <li>Item 1<button class="btn">click</button></li>
      <li>Item 2<button class="btn">click</button></li>
      <li>Item 3<button class="btn">click</button></li>
      <li>Item 4<button class="btn">click</button></li>
      <li>Item 5<button class="btn">click</button></li>
    </ul>