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?
user7522621
source
share