Return each DOM element to an array

In my experiment, I used three ways to return each HTML element to an array:

  • elementsArray.forEach(function(elem) {})
  • [].forEach(elementsArray, function(elem) {})
  • Array.prototype.forEach.call(elementsArray, function(elem) {})


In my HTML, I have the following elements:

<section id="example">
  <div></div>
  <div></div>
  <div></div>
</section>


First example:

var query = document.querySelector.bind(document);

query('#example').children.forEach(function(elem) {
  console.log(elem);
})

Uncaught TypeError: query (...). children.forEach is not a function


Second example:

var query = document.querySelector.bind(document);

[].forEach(query('#example').children, function(elem) {
  console.log(elem);
})

Uncaught TypeError: #<HTMLCollection>not a function


Third example:

var query = document.querySelector.bind(document);

Array.prototype.forEach.call(query('#example').children, function(elem) {
  console.log(elem)
})

<div></div>
<div></div>
<div></div>

My question is what makes these three different from each other in terms of returning DOM elements? And when should I use each?

+4
source share
2 answers

First example:

A property of an childrenelement is HTMLCollectionthat does not have a method forEach. Therefore, this option does not work.

Second example:

[].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);
})

forEach NodeList , . polyfill, .

+6

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

0

Source: https://habr.com/ru/post/1676884/


All Articles