How can I convert a NodeList to an array in JavaScript?
Richard W
richard w profile pic

Converting aNodeList to an array in JavaScript allows you to leverage the full range of array methods and properties. Here's a step-by-step approach to converting aNodeList to an array: 1. Using the spread operator: - The spread operator (...) can be used to convert an iterable object, such as aNodeList, to an array.

1
2
3
4

   const nodeList = document.querySelectorAll('.my-class');
   const array = [...nodeList];
   

In this example,document.querySelectorAll('.my-class') retrieves all elements with the class name 'my-class' and returns aNodeList. The spread operator[...nodeList] converts theNodeList to an array by spreading its elements into a new array. 2. Using the Array.from() method: - TheArray.from() method creates a new array instance from an array-like or iterable object, includingNodeList.

1
2
3
4

   const nodeList = document.querySelectorAll('.my-class');
   const array = Array.from(nodeList);
   

In this approach,Array.from(nodeList) converts theNodeList to an array by creating a new array instance with the elements of theNodeList. 3. Using the Array.prototype.slice() method: - Theslice() method of an array can be applied to aNodeList by borrowing it using thecall() method.

1
2
3
4

   const nodeList = document.querySelectorAll('.my-class');
   const array = Array.prototype.slice.call(nodeList);
   

In this example,Array.prototype.slice.call(nodeList) borrows theslice() method from theArray prototype and applies it to theNodeList. This effectively converts theNodeList to an array. Here's an example that demonstrates the conversion of aNodeList to an array:

1
2
3
4
5

const nodeList = document.querySelectorAll('.my-class');
const array = [...nodeList];

console.log(array); // Output: An array with the elements from the NodeList

In this example, thequerySelectorAll() method retrieves all elements with the class name 'my-class' and returns aNodeList. The spread operator[...nodeList] is used to convert theNodeList to an array, which is then stored in thearray variable. The resultingarray variable holds an array with the elements from theNodeList. By converting aNodeList to an array, you can utilize array methods likeforEach(),map(),filter(), and more, making it easier to manipulate and work with the collection of elements.