return elements that match specified CSS selector(s)

How do I convert the NodeList from querySelectorAll() to an array?

Answers:

  • You can convert a NodeList from querySelectorAll() to an array in a few different ways. Here are some common methods:

    1. Using the Spread Operator

    The spread operator (...) can be used to convert a NodeList into an array easily:

    const elements = document.querySelectorAll('your-selector');
    const elementsArray = [...elements];
    

    2. Using Array.from()

    The Array.from() method creates a new array instance from an array-like or iterable object:

    const elements = document.querySelectorAll('your-selector');
    const elementsArray = Array.from(elements);
    

    3. Using Array.prototype.slice.call()

    You can also use the slice method from Array.prototype to achieve the same result:

    const elements = document.querySelectorAll('your-selector');
    const elementsArray = Array.prototype.slice.call(elements);
    

    4. Using forEach with an empty array

    You can also create an empty array and use forEach to populate it:

    const elements = document.querySelectorAll('your-selector');
    const elementsArray = [];
    elements.forEach(element => elementsArray.push(element));
    

    Any of these methods will give you an array containing the elements selected by your query. The first two methods (spread operator and Array.from()) are the most commonly used due to their conciseness and readability.

Related Questions: