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.
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With