简体   繁体   中英

JavaScript HtmlCollection loop never returns second element

i know there are answers on how to access and iterate over a HtmlCollection, but it just doesn't work for me here:
I got some elements with the class "tabSheetActive", the amount of these can be 1 or more.
I access them with:

var activeTabSheets = document.getElementsByClassName('tabSheetActive');
console.log('Active sheets amount: ' + activeTabSheets.length); // outputs 2

Logging the collection outputs the following:

[div.tabSheetActive.sheet_512_0, div.tabSheetActive.sheet_512_0]

After that i try to iterate over them and manipulate their classes like this:

for (var i = 0; i < activeTabSheets.length; i++) { // just iterates one time
    var activeTabSheet = activeTabSheets[i];
    console.log("Index: " + i); // outputs 0 
    console.log(activeTabSheet); // outputs first element
    var newClassName = activeTabSheet.className.replace('tabSheetActive', 'tabSheet');
    activeTabSheet.className = newClassName;
}

The tricks with [].forEach.call(activeTabSheets, function(activeTabSheet) { //code here }); don't work either for me. It just iterates once.
It must be something really stupid but i have been debugging and ripping my hair out over this for hours.

getElementsByClassName returns a live HTMLCollection.

This line:

activeTabSheet.className.replace('tabSheetActive', 'tabSheet');

Stops the first item in the list from being a member of the class. Consequently it is removed and everything else is shuffled down (so the element that was at index 1 moves to index 0).


To deal with this you can:

  • Use querySelectorAll which returns a non-live NodeList
  • Loop over the HTMLCollection backwards
  • Use a while loop, test the length of the HTMLCollection, and always modify index 0 .
  • Copy all the values into an array before looping over that

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM