return elements that match specified CSS selector(s)

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

Answers:

  • You can convert a NodeList obtained from querySelectorAll() into an array using various methods. Here are a few common approaches:

    1. Using Array.from()

    The simplest way to convert a NodeList to an array is by using the Array.from() method.

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

    2. Using the Spread Operator

    You can also use the spread operator (...) inside an array literal to convert the NodeList.

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

    3. Using Array.prototype.slice()

    If you want a more traditional way, you can use the slice method from Array.prototype.

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

    4. Using forEach (if you want to create a custom array)

    If you want to manually iterate through the NodeList, you can also create an array using forEach.

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

    Any of these methods will successfully convert a NodeList into an array, so you can choose the one that fits your coding style or preferences best!

Related Questions: