I have a strange behavior in my very simple code. I want to remove()
all buttons with the class btn
from the DOM after a button has been clicked.
In my function removeAllBtns()
I have two console outputs. The correct number of buttons is displayed. But the second element is always not deleted.
Why is that? I am probably missing something very simple here. Thanks in advance.
let btns = document.getElementsByClassName('btn');
for (var i = 0; i < btns.length; i++) {
let button = btns[i];
button.addEventListener('click', function (e) {
removeAllBtns();
});
}
function removeAllBtns() {
console.log('btns length',btns.length)
for (let j = 0; j < btns.length; j++) {
console.log(j, btns[j])
btns[j].remove();
}
}
.btn{
color: red;
}
<button class="btn">1</button>
<button class="btn">2</button>
<button class="btn">3</button>