return elements that match specified CSS selector(s)

What is the return value of querySelectorAll?

Answers:

  • The querySelectorAll method in the DOM (Document Object Model) returns a NodeList object. This NodeList contains all the elements that match the specified CSS selectors. It is a static collection, meaning that it does not update automatically if the document changes after the method is called.

    Here's a basic example of how to use querySelectorAll:

    const elements = document.querySelectorAll('.my-class');
    console.log(elements); // This will log a NodeList of all elements with the class 'my-class'.
    

    You can then iterate over this NodeList using methods like forEach, or convert it to an array if you need to use array methods on it. Keep in mind that the NodeList returned is not an Array, but it does have a forEach method available in modern browsers. If you need to convert it to an Array, you can use the spread operator or Array.from:

    const elementsArray = Array.from(elements);
    // or
    const elementsArray = [...elements];
    

Related Questions: