Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 623
jsLearner Avatar asked Mar 04 '23 09:03

jsLearner


2 Answers

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>
like image 124
CertainPerformance Avatar answered Mar 16 '23 01:03

CertainPerformance


You can get the button and add event to it , that on click it will find its parent and will remove it

document.querySelectorAll(".btn").forEach(function(i) {
  i.addEventListener('click', function() {
    this.parentNode.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>
like image 27
brk Avatar answered Mar 16 '23 00:03

brk