return elements that match specified CSS selector(s)

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

Answers:

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

    1. Using Array.from()

    Array.from() is a built-in method that creates a new array from an array-like or iterable object like a NodeList.

    const nodeList = document.querySelectorAll('selector');
    const array = Array.from(nodeList);
    

    2. Using the Spread Operator

    You can also use the spread operator (...) to expand the NodeList into an array.

    const nodeList = document.querySelectorAll('selector');
    const array = [...nodeList];
    

    3. Using Array.prototype.slice()

    You can use Array.prototype.slice.call() to convert the NodeList to an array.

    const nodeList = document.querySelectorAll('selector');
    const array = Array.prototype.slice.call(nodeList);
    

    4. Using forEach

    If you prefer a more manual approach, you can iterate through the NodeList and push the elements into a new array.

    const nodeList = document.querySelectorAll('selector');
    const array = [];
    nodeList.forEach(node => array.push(node));
    

    Example Usage

    Suppose you want to convert all <div> elements on a page to an array:

    const divsNodeList = document.querySelectorAll('div');
    const divsArray = Array.from(divsNodeList); // or use any of the methods above
    
    console.log(divsArray); // Now you can use divsArray as a regular array
    

    You can choose any of the methods above based on your preference or use case. The most modern and concise approaches are Array.from() and the spread operator.