0

I have a page with 100 elements of the same class name. I use JavaScript to generate them such as below:

for(let i = 0; i < 100; i++){
  var element = document.createElement("div");
  element.classList.add("hi");
  element.innerHTML="hi";
  document.body.appendChild(element);
}
console.log(document.getElementsByClassName("hi").length); //This logs how many there are

I then tried to delete them. However, that only deleted half of them. Result can be seen here:

for(let i = 0; i < 100; i++){
  var element = document.createElement("div");
  element.classList.add("hi");
  element.innerHTML="hi";
  document.body.appendChild(element);
}
var elements = document.getElementsByClassName("hi");
for(let i = 0; i < elements.length; i++){
  elements[i].remove();
}
console.log(document.getElementsByClassName("hi").length);

As seen above, it logs 50 elements, which means my FOR loop only deleted half of them.

Why is this happening and how do I fix it?

Rep Hunter
  • 15
  • 5
  • You have done a logical error and nothing else, Your i keeps on increasing and element.length keeps decreasing after every iteration and meets half way at 50 and your loop stops. thats why only half of your element is vanishing – Kaustubh Jan 25 '21 at 20:19
  • You should keep elements.length in separate variable after adding and before deleting elements and loop your i to that variable when deleting them – Kaustubh Jan 25 '21 at 20:20
  • No, you should just do `Array.from(document.getElementsByClassName("hi")).forEach((elem) => elem.remove());`. – Sebastian Simon Jan 25 '21 at 20:44
  • @Kaustubh That makes complete sense. Thank you. – Rep Hunter Jan 25 '21 at 21:24

0 Answers0