S
S
Swaer2018-03-27 22:17:35
JavaScript
Swaer, 2018-03-27 22:17:35

Only the first element of the list is removed, why?

var removeC = document.querySelector('li');
for (var i = 0; i < removeC.length; i++) {
removeC[i].onclick = function() {
if (removeC.parentNode){
removeC.parentNode.removeChild(removeC);
removeC.removeChild(removeC);
}
}
}
removeC.onclick = function(){
if (removeC.parentNode) {
removeC.parentNode.removeChild(removeC);
}
}
Why does the function apply only to the first element? How to make it apply to all elements and which will be created using the button, but if you delete the already created li and create using the button, it does not even remove the first one, as before

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Varlamov, 2018-03-27
@bes_internal

You initially have only one first element in removeC, not all. Use querySelectorAll
In the second part of the question, as I understand it, you are asking why it does not constantly hang events on newly added elements? Well, because it passes through the elements once when called and that's it, and new ones are already created without this event

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question