Looping through a nodelist JS

后端 未结 1 1930
独厮守ぢ
独厮守ぢ 2021-01-26 00:10

My question is : iam trying to get through the NODELIST of class Hot . And i want to change their className to \'cool\' . When iam using the for loop it seems that its the seco

相关标签:
1条回答
  • 2021-01-26 01:09

    getElementsByClassName returns a live node list. Once you've changed the class on one element the node list updates to reflect this so your index will always be out.

    One way to mitigate this is to convert the node list to a static node list using Array.slice.call:

    var elements = [].slice.call(document.getElementsByClassName('hot'));
    

    DEMO

    Another way, as you point out, is to use document.querySelectorAll which returns a static node list:

    document.querySelectorAll('.hot');
    

    DEMO

    0 讨论(0)
提交回复
热议问题