Reputation: 63
I am only discovering the DOM as a beginner, and now I am a little bit confused.
I have read in one article, that nodeList is just an array-like element - it shows up in console as an array but it is not possible to use array methods (like forEach or map) on it. But when I tried this (in table made with JS, function table()):
let node = document.querySelectorAll('td')
node.forEach(function(node){
node.style.border = 'thin solid #000';
node.textContent = 'cell';
console.log(node);
})
It worked as I wanted - as an array.
Apart from it, this code created only empty array, without nodeList inside:
let node = document.querySelectorAll('td')
let nodeToArray = Array.apply(node);
console.log(nodeToArray);
I tried spread operator:
let nodeToArray = [document.querySelectorAll('td')]
And it turned nodeList to array, but only with one number - maybe it's caused by creating td with looping?
And, of course, the forEach method didn't work with "Cannot set property 'border' of undefined."
let nodeToArray = [document.querySelectorAll('td')]
nodeToArray.forEach(function(nodeToArray){
nodeToArray.style.border = 'thin solid #000';
nodeToArray.textContent = 'cell';
console.log(nodeToArray);
So, how am I supposed to change nodeList to array? Or is it possible to work with nodeList more, as it was array? (I want to create chessboard and therefore I need to use this array for if-else conditional statement to make odd/even cells.)
Upvotes: 3
Views: 445
Reputation: 1118
You need to transform the node
in an actual Array object. You can use Array.from to do that:
const nodes = document.querySelectorAll('div')
const nodesArray = Array.from(nodes)
nodesArray.forEach(console.log)
If in doubt, you can use Array.isArray to check if an object is an array:
const nodes = document.querySelectorAll('div')
console.log(Array.isArray(nodes)) // false
const nodesArray = Array.from(nodes)
console.log(Array.isArray(nodesArray)) // true
Upvotes: 4
Reputation: 2134
Within my answer I thought that I'd include multiple approaches, a mixture of ES5 and ES6, here's a couple of simple ways in which you can achieve this.
As advised in the MDN docs, if you want to have any support for IE, you'd want to use the first implementation that I've provided, if you're not so worries about supporting older browsers the you can easily use either of the ES6 solutions that I've provided.
Personally I prefer using the destructuring approach, but each to their own.
// ES5
var notArray = document.querySelectorAll("input");
var array = Array.prototype.slice.call(notArray);
// ES6
const notArray1 = document.querySelectorAll("input");
const array1 = [...notArray1];
const array2 = Array.from(notArray1);
// Tests
console.log(Array.isArray(array));
console.log(Array.isArray(array1));
console.log(Array.isArray(array2));
console.log(Array.isArray(notArray));
console.log(Array.isArray(notArray1));
<input>
<input>
<input>
<input>
<input>
<input>
Upvotes: 1