return elements that match specified CSS selector(s)

How to check if querySelectorAll returned any elements?

Answers:

  • To check if querySelectorAll returned any elements in JavaScript, you can check the length of the returned NodeList. The querySelectorAll method returns a NodeList object that contains all the elements that match the specified CSS selector(s). If no elements match, the length of the NodeList will be 0.

    Here’s how you can do it:

    // Replace 'yourSelector' with the CSS selector you want to check
    const elements = document.querySelectorAll('yourSelector');
    
    // Check if any elements were found
    if (elements.length > 0) {
        console.log('Found elements:', elements);
    } else {
        console.log('No elements found.');
    }
    

    Example:

    Let's say you want to check for all <div> elements with the class example:

    const divs = document.querySelectorAll('div.example');
    
    if (divs.length > 0) {
        console.log('Found divs:', divs);
    } else {
        console.log('No divs found.');
    }
    

    This will print the list of found <div> elements if there are any matching the selector; otherwise, it will indicate that no matching elements were found.

Related Questions: