Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript remove not removing all elements

Please refer fiddle - http://jsfiddle.net/fkwwyvz8/

x = document.getElementsByClassName("buddy_blocks");
for(i=0;i<x.length;i++)
    x[i].remove();

Click on the last button, and it had to remove all the other buttons, but it does not and only removes some of them, not sure why? And any way to remove all those buttons?

like image 453
nikhil rao Avatar asked Jan 08 '23 23:01

nikhil rao


2 Answers

Since you appear to have jQuery in your code already, you can just use this to remove all buttons:

$(".buddy_blocks").remove();

Your attempt was not working for two reasons:

  1. document.getElementsByClassName() returns a dynamic nodeList that changes underneath you each time you remove an element which causes you to miss elements in your iteration
  2. Because a DOM element does not have a .remove() method (in most browsers anyway - it is a proposed method, but isn't widely available yet). The parent has a .removeChild() method you can use instead.

In plain Javascript, you could set up your iteration backwards so that when you remove elements and when this causes the dynamic HTMLCollection to change, it will not mess up your iteration because the changes will be the elements that you have already passed by. And, switch to use .removeChild() like this:

function f() {
    var x = document.getElementsByClassName("buddy_blocks");
    for(var i = x.length - 1; i >= 0; i--) {
        x[i].parentNode.removeChild(x[i]);
    }
}

Also, please use var on all variables that are intended to be local to your function so you are not creating "accidental global variables" which will cause hard to figure out bugs at some time in the future.


Or, in modern browsers as of 2021, you can use document.querySelectorAll() (because it doesn't return a live collection and is iterable) and you can use .remove() since all modern browsers support it:

function f() {
    const items = document.querySelectorAll(".buddy_blocks");
    for (let item of items) {
         item.remove();
    }
}
like image 88
jfriend00 Avatar answered Jan 11 '23 11:01

jfriend00


When iterating over an array and modifying it, start at the last index to avoid side effects to the current index position when you remove items

$("#c").click(function() {
  f();
});

function f() {
  x = document.getElementsByClassName("buddy_blocks");
  for(i=x.length-1;i>=0;i--)
    x[i].remove();
}
like image 28
kindasimple Avatar answered Jan 11 '23 13:01

kindasimple