如何循环遍历document.querySelectorAll()方法返回的结果
生活随笔
收集整理的這篇文章主要介紹了
如何循环遍历document.querySelectorAll()方法返回的结果
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
使用JavaScript的forEach方法,我們可以輕松的循環一個數組,但如果你認為document.querySelectorAll()方法返回的應該是個數組,而使用forEach循環它:
/* Will Not Work */ document.querySelectorAll('.module').forEach(function() {});
執行上面的代碼,你將會得到執行錯誤的異常信息。這是因為,document.querySelectorAll()返回的不是一個數組,而是一個NodeList。
對于一個NodeList,我們可以用下面的技巧來循環遍歷它:
var divs = document.querySelectorAll('div');[].forEach.call(divs, function(div) {// do whateverdiv.style.color = "red"; });當然,我們也可以用最傳統的方法遍歷它:
var divs = document.querySelectorAll('div'), i;for (i = 0; i < divs.length; ++i) {divs[i].style.color = "green"; }還有一種更好的方法,就是自己寫一個:
?
// forEach method, could be shipped as part of an Object Literal/Module var forEach = function (array, callback, scope) {for (var i = 0; i < array.length; i++) {callback.call(scope, i, array[i]); // passes back stuff we need} };// 用法: // optionally change the scope as final parameter too, like ECMA5 var myNodeList = document.querySelectorAll('li'); forEach(myNodeList, function (index, value) {console.log(index, value); // passes index + value back! });還有一種語法:for..of?循環,但似乎只有Firefox支持:
/* Be warned, this only works in Firefox */var divs = document.querySelectorAll('div );for (var div of divs) {div.style.color = "blue"; }最后是一種不推薦的方法:給NodeList擴展一個forEach方法:
NodeList.prototype.forEach = Array.prototype.forEach;var divs = document.querySelectorAll('div').forEach(function(el) {el.style.color = "orange"; })
轉載于:https://www.cnblogs.com/xupeiyu/p/5067115.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的如何循环遍历document.querySelectorAll()方法返回的结果的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VHDL基本门电路和数值比较器的设计
- 下一篇: VHDL简易电子琴的设计