<div id="par">
<span id="a1"></span>
<span id="a2"></span>
<div id="par2">
<span id="a3"></span>
<span id="a4"></span>
</div>
</div>
<script>
var ele = document.querySelectorAll('#par span');
for( var p of ele ){
console.log(p);
}
</script>
当我运行此代码时,我看到错误
未捕获的TypeError:ele [Symbol.iterator]不是函数
如何解决这个问题?
答案 0 :(得分:15)
将NodeList
转换为Array
以使其以可迭代的形式生成,使用Array.from()
进行转换。
<div id="par">
<span id="a1"></span>
<span id="a2"></span>
<div id="par2">
<span id="a3"></span>
<span id="a4"></span>
</div>
</div>
<script>
var ele = document.querySelectorAll('#par span');
for (var p of Array.from(ele)) {
console.log(p);
}
</script>
有关详细信息,请参阅以下问题:Are HTMLCollection and NodeList iterables?