convert nodelist to node array in javascript

To convert a NodeList to an array of nodes in JavaScript, there are different approaches. Here are two of them:

Using Array.from() method

The Array.from() method creates a new Array instance from an array-like or iterable object. Since a NodeList is an array-like object, we can use this method to convert it to an array.

index.tsx
const nodeList = document.querySelectorAll('p');
const nodeArray = Array.from(nodeList);
89 chars
3 lines

Using the spread operator

The spread operator allows us to expand an iterable object into individual elements. We can use it together with the Array constructor to create a new array from the NodeList.

index.tsx
const nodeList = document.querySelectorAll('p');
const nodeArray = [...nodeList];
82 chars
3 lines

In both cases, the result is an array of nodes, which can be manipulated using array methods.

gistlibby LogSnag