Search code examples
javascriptarraysdomnodelist

Node to Array in DOM JS, how it works?


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.)


Solution

  • 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