JavaScript HtmlCollection loop never returns second element

耗尽温柔 提交于 2019-12-04 06:20:40

问题


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 index 0.
  • Copy all the values into an array before looping over that


来源:https://stackoverflow.com/questions/30506113/javascript-htmlcollection-loop-never-returns-second-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!