return elements that match specified CSS selector(s)

Can NodeList returned by querySelectorAll() be converted to an array?

Answers:

  • Yes, a NodeList returned by querySelectorAll() can be converted to an array. A NodeList is similar to an array but does not have all the array methods. To convert it into a true array, you can use several methods. Here are a few common approaches:

    1. Using Array.from()

    This method creates a new array instance from an array-like or iterable object.

    const nodeList = document.querySelectorAll('div'); // or any other selector
    const array = Array.from(nodeList);
    

    2. Using the Spread Operator

    ES6 provides the spread operator that can be used to spread the values of an iterable into an array.

    const nodeList = document.querySelectorAll('div'); // or any other selector
    const array = [...nodeList];
    

    3. Using Array.prototype.slice()

    You can also use Array.prototype.slice() to convert a NodeList to an array.

    const nodeList = document.querySelectorAll('div'); // or any other selector
    const array = Array.prototype.slice.call(nodeList);
    

    All of these methods will give you a true array containing the same elements as the NodeList, allowing you to use array methods like .map(), .filter(), and .forEach().

Related Questions: