JavaScript HtmlCollection loop never returns second element

后端 未结 1 1789
梦如初夏
梦如初夏 2021-01-27 11:14

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\", t

相关标签:
1条回答
  • 2021-01-27 11:41

    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
    0 讨论(0)
提交回复
热议问题