return elements that match specified CSS selector(s)

How do I convert a NodeList to an array when using querySelectorAll?

Answers:

  • When you use querySelectorAll in JavaScript, it returns a NodeList, which is similar to an array but not actually an array. If you want to convert a NodeList to an actual array, you can use several methods. Here are a few common approaches:

    1. Using Array.from()

    The simplest and most modern way is to use Array.from():

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

    2. Using the Spread Operator

    Another modern method is to use the spread operator ... to spread the NodeList into an array:

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

    3. Using Array.prototype.slice

    For older browsers that may not support modern methods, you can use Array.prototype.slice:

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

    4. Using forEach to Push to an Array

    You can also manually push elements from the NodeList into a new array:

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

    Usage Example

    Here’s how you can use the first method in a real example:

    // Select all <div> elements
    const divs = document.querySelectorAll('div');
    // Convert NodeList to array
    const divArray = Array.from(divs);
    
    // Now you can use array methods on divArray
    divArray.forEach(div => {
        console.log(div.innerText);
    });
    

    Choose any of the above methods depending on your coding preference and the browser support you need to maintain. The first two methods (Array.from() and the spread operator) are preferred for their simplicity and clarity.

Related Questions: