kkmoslehpour kkmoslehpour - 1 month ago 10
HTML Question

Javascript chrome extension to click all elements on the page only updating half

I am trying to write a simple extension to click all the buttons on a web page that have the same element name, however, when I print the console log without the "updateArray[a].click()" it prints the correct array length. But when I add the "updateArray[a].click()" back it only click half the array length which is weird. How is it that when I add that line back it only clicks half of the button on the elements page, also when i add that line back my array length cuts in half?

function clickUpdate() {
var updateArray = document.getElementsByClassName("updateButton");

for(var a=0;a<updateArray.length;a++){
updateArray[a].click();
console.log("this is the array:" + a);
}
console.log("this is the array legnth: " + updateArray.length);
}
clickUpdate();

Answer

does the result of updateArray[a].click(); remove the updateButton class from the element? because updateArray is not actually an array, it's a HTMLCollection, which will change if you remove that class from any of it's elements ... i.e. if you remove the class updateButton from any of the elements in that collection, that collection will shrink by 1 member - which is why you end up clicking only half the elements

I suggest using something like this

function clickUpdate() {
    var updateArray = document.getElementsByClassName("updateButton");
    [].slice.call(updateArray).forEach(function(item) {
        item.click();
    });
    console.log("this is the array legnth: " + updateArray.length);
}
clickUpdate();

this uses the array#slice function to create a (static) copy of the data in updateArray, then uses forEach on this new array to do the clicking

alternatively, if you use querySelectorAll what you end up with is a NodeList - which isn't a "live" list like an HTMLCollection you get with `getElementsByClassName

function clickUpdate() {
    var updateArray = document.querySelectorAll(".updateButton");

     for(var a=0;a<updateArray.length;a++){ 
     updateArray[a].click(); 
     console.log("this is the array:" + a);
}
console.log("this is the array legnth: " + updateArray.length);
}
clickUpdate(); 
Comments