return elements that match specified CSS selector(s)

How do I get the count of elements selected by querySelectorAll()?

Answers:

  • To get the count of elements selected by querySelectorAll(), you can simply use the length property of the NodeList that is returned by this method. Here's a step-by-step example:

    1. Use document.querySelectorAll() to select the elements you want.
    2. Access the length property of the resulting NodeList.

    Here's a sample code snippet:

    // Select all <p> elements in the document
    const paragraphs = document.querySelectorAll('p');
    
    // Get the count of selected elements
    const count = paragraphs.length;
    
    // Log the count to the console
    console.log(`Number of paragraphs: ${count}`);
    

    In this example, if there are 5 <p> elements in the document, the output will be:

    Number of paragraphs: 5
    

    This method works for any CSS selector you use with querySelectorAll().

Related Questions: