Javascript: Getelementsbyclassname Not Giving All Elements
Well i put tablerows with a classname 'gone' in my Html like this: text text
Solution 1:
the HTMLCollection returned by getElementsByClassName
is a LIVE LIST ... by changing the class, you change the list during the for loop!
One solution is to "copy" the list to an array
var arrayelements=Array.prototype.slice.call(document.getElementsByClassName('gone'));
var arrlength=arrayelements.length;
for(var i=0;i<arrlength;i++){
arrayelements[i].setAttribute("class","there");
console.log(arrayelements);
}
Another method would be to start at the end of the list and work backwards
var arrayelements=document.getElementsByClassName('gone');
var arrlength=arrayelements.length;
for(var i=arrayelements.length-1;i>=0;i--){
arrayelements[i].setAttribute("class","there");
console.log(arrayelements);
}
or another - always work on the first element, seeing as you're always shrinking the length
var arrayelements=document.getElementsByClassName('gone');
while(arrayelements.length) {
arrayelements[0].setAttribute("class","there");
}
I would recommend the first as the easiest to work with, and avoid the last method :p
Post a Comment for "Javascript: Getelementsbyclassname Not Giving All Elements"