return elements that match specified CSS selector(s)

How do I get the number of elements returned by querySelectorAll()?

Answers:

  • In JavaScript, when you use the querySelectorAll() method, it returns a NodeList containing all the elements that match the specified CSS selector(s). To get the number of elements returned by querySelectorAll(), you can use the .length property of the NodeList. Here's how you can do it:

    // Example: Select all `<p>` elements in the document
    const elements = document.querySelectorAll('p');
    
    // Get the number of elements
    const numberOfElements = elements.length;
    
    console.log(numberOfElements); // Outputs the number of <p> elements found
    

    In this example, elements is a NodeList of <p> elements from the document, and elements.length gives you the count of those elements. You can replace 'p' with any other valid CSS selector to count the elements that match that selector.

Related Questions: