Ad

HTML Collection - Remove Elements During While Loop

- 1 answer

I have an HTML Collection and I am wanting to remove items 0-2 and items 19-28 when the second item in the collection is clicked. What am I missing here?

//Add on OnClick command to the second element of the HTML collection.
document.getElementsByClassName("esg-filterbutton")[1].addEventListener("click", myFunction);

//Remove elements 0-2 and 19-28 from the collection.
function myFunction(){
  while (i<3 && i>18 && i<29){
  .esg-filterbutton.remove();
 }
}

Thanks,

Jonathan

Ad

Answer

You seem to have forgotten to actually reference the collection, also your loop is invalid.

This code should do what you want:

document.getElementsByClassName("esg-filterbutton")[1].addEventListener("click", myFunction);


var filters = document.getElementsByClassName("someClassName");
//Remove elements 0-2 and 19-28 from the collection.
function myFunction(){
 for (var i = 0;i<29; i++){
  if (i === 3) { // Skip elements 3 to 18
    i = 19;
    continue;
  }
  filters[i].remove();
 }
}
Ad
source: stackoverflow.com
Ad