【发布时间】:2017-05-11 04:15:06
【问题描述】:
我在实验中使用了 3 种方法来返回数组中的每个 HTML 元素:
elementsArray.forEach(function(elem) {})[].forEach(elementsArray, function(elem) {})Array.prototype.forEach.call(elementsArray, function(elem) {})
在我的 HTML 中,我有以下元素:
<section id="example">
<div></div>
<div></div>
<div></div>
</section>
第一个例子:
var query = document.querySelector.bind(document);
query('#example').children.forEach(function(elem) {
console.log(elem);
})
未捕获的 TypeError: query(...).children.forEach 不是函数
第二个例子:
var query = document.querySelector.bind(document);
[].forEach(query('#example').children, function(elem) {
console.log(elem);
})
未捕获的类型错误:
#<HTMLCollection>不是函数
第三个例子:
var query = document.querySelector.bind(document);
Array.prototype.forEach.call(query('#example').children, function(elem) {
console.log(elem)
})
<div></div><div></div><div></div>
我的问题是,是什么让这三个在返回 DOM 元素方面彼此不同?我应该什么时候使用它们?
【问题讨论】:
-
可以使用
querySelectorAll('#example > *')查询#example的所有直系子代。
标签: javascript html arrays