将每个DOM元素作为数组返回

4

在我的实验中,我使用了三种方法来返回一个数组中的每个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);
})

未捕获的类型错误: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在返回DOM元素方面有何不同?什么时候应该使用每个元素?

您可以使用querySelectorAll('#example> *')查询#example的所有直接子元素。 - Omri Luzon
2个回答

6

第一个例子:

元素的children属性是一个HTMLCollection,它没有forEach方法。因此这个选项不可行。

第二个例子:

[].forEach(query('#example').children, function(elem) {

这段代码试图将子元素的HTMLCollection用作回调函数。但是这不是一个函数,所以它不起作用。

你可以这样做:

[].forEach.call(query('#example').children, function(elem) {

第三个例子:

Array.prototype.forEach.call 大致相当于 [].forEach.call 方法,但它不会创建一个新的数组对象。这个方法可以使用。

另一种选择:

另一种略有不同的选择是使用 querySelectorAll,它返回一个NodeList,其中包含了 forEach 方法。

var queryAll = document.querySelectorAll.bind(document);

queryAll('#example > *').forEach(function(elem) {
  console.log(elem);
})

然而,NodeListforEach 方法是一个较新的添加,浏览器支持仍然缺乏。不过,你可以使用填充方法来解决这个问题。


那这是否意味着有些方法和属性只适用于HTMLCollection和NodeList? - user7522621

0
你应该使用 querySelectorAll
<section>
  <div class="foo">Foo</div>
  <div class="foo">Foo</div>
  <div class="foo">Foo</div>
</section>

var section = document.querySelector('section');
section.querySelectorAll('.foo').forEach(function(e) {
    console.log(e);
})

这里是一个JSFiddle


OP正在使用children集合。 - RobG
@RobG 请看我的修订后的答案。 - Gabe Rogan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接