问题
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.
回答1:
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 index0
. - Copy all the values into an array before looping over that
来源:https://stackoverflow.com/questions/30506113/javascript-htmlcollection-loop-never-returns-second-element