What's the best way to loop through a set of elements in JavaScript?

前端 未结 14 1999
清歌不尽
清歌不尽 2020-11-27 06:34

In the past and with most my current projects I tend to use a for loop like this:

var elements = document.getElementsByTagName(\'div\');
for (var i=0; i

        
14条回答
  •  借酒劲吻你
    2020-11-27 07:02

    I had a very similar problem earlier with document.getElementsByClassName(). I didn't know what a nodelist was at the time.

    var elements = document.getElementsByTagName('div');
    for (var i=0; i

    My issue was that I expected that elements would be an array, but it isn't. The nodelist Document.getElementsByTagName() returns is iterable, but you can't call array.prototype methods on it.

    You can however populate an array with nodelist elements like this:

    var myElements = [];
    for (var i=0; i

    After that you can feel free to call .innerHTML or .style or something on the elements of your array.

提交回复
热议问题