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:
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
- 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();
}
}
x
array – Ere