Why are my missing JavaScript elements for the loop?

I have a loop forthat goes through a set of elements, removing a class 'selected'from each. However, it skips every second iteration. I found that I can get around this by adding j--, which I think is good, except for lengthening my code. But I wonder if anyone can explain why it is skipping and maybe offering a more concise way of writing this code? (I am still studying the ropes and want me to understand what is happening.)

var selections = document.getElementsByClassName(name + 'selected');
for (var j = 0; j < selections.length; j++) {
  selections[j].classList.remove('selected');
  j--; // the fix
}

// where name is a present variable

Thank you for your time!

+4
source share
2 answers

, getElementsByClassName() live HtmlCollection; , HtmlCollection , "" , .

:

var selections = document.getElementsByClassName(name + 'selected');
while (selections.length) {
    selections[0].classList.remove('selected');
}

... .


, Paul Roub , ;

for (var j = selections.length-1; j >= 0; j--) {
  selections[j].classList.remove('selected');
}

HtmlCollection, ;

var selections = Array.prototype.slice.call(document.getElementsByClassName(name + 'selected'));
for (var j = 0; j < selections.length; j++) {
  selections[j].classList.remove('selected');
}

... , , querySelectorAll ;

var selections = document.querySelectorAll('.' + name + 'selected');
for (var j = 0; j < selections.length; j++) {
  selections[j].classList.remove('selected');
}
+9

getElementsByClassName - HTML-, , , . , , , , .

var selections = document.getElementsByClassName('selected');
console.log("before: ", selections.length);
selections[0].classList.remove("selected");
console.log("after: ", selections.length);
<div class="selected"></div>
<div class="selected"></div>
<div class="selected"></div>
<div class="selected"></div>
<div class="selected"></div>
Hide result

, .

- while.

var selections = document.getElementsByClassName('selected');
while(selections.length) {
    selections[0].classList.remove("selected");
}
+1

Source: https://habr.com/ru/post/1651804/


All Articles