user8758206
user8758206

Reputation: 2191

Creating a simple array from a node list not working as an IIFE

I'm trying to create an array on the fly using a variable declaration and an IIFE, although it seems to not be adding each item to the array. Take this html for example:

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

And this javascript:

const divs = document.querySelectorAll('div');

const divsTwo = [...divs]; // not IE compatible

const divsThree = (function() {
    let arr = [];

    for (let item of divs) {
        arr.push[item];
    }

    return arr;
})();

// logging
console.log(divs); // correctly logs node list
console.log(divsTwo); // correctly logs array (right?)
console.log(divsThree); //* logs an empty (incorrect) array

I essentially want to just replicate divsTwo (via divsThree) so that it's IE compatible. Can someone point out why the third variable isn't the same as the second? Thanks for any help here

Codepen: https://codepen.io/ns91/pen/JjdrZyP

Upvotes: 1

Views: 36

Answers (3)

Joshua Kleveter
Joshua Kleveter

Reputation: 1769

As mentioned in other answers it looks like you just have a typo and are trying to call arr.push[] instead of arr.push() (note the use of parens instead of brackets).

However, as far as IE goes, the standard way to make the list of DOM nodes an array is as follows:

var divs = document.querySelectorAll('div');

var divsArr = Array.prototype.slice.call(divs);

Note that I'm using var as const isn't IE compatible either.

Upvotes: 1

NaSir HuSSaiN
NaSir HuSSaiN

Reputation: 315

the issue is in your for loop i think. Try

 for (let item in divs) {
        arr.push[item];
    }

Upvotes: 0

Guest
Guest

Reputation: 26

A comment shows you are using Array.prototype.push incorrectly. Still there's a better way.

Use Array.from to turn any iterable into an array -

const divs =
  document.querySelectorAll('div')

const myArr =
  Array.from(divs)

console.log(myArr)
// [div, div, div, ..., div]

Upvotes: 1

Related Questions