return elements that match specified CSS selector(s)

What happens if no elements match the selector in querySelectorAll()?

Answers:

  • If no elements match the selector provided to querySelectorAll(), the method will return an empty NodeList. The NodeList will have a length property of 0, indicating that there are no matching elements in the document. You can safely check the length of the returned NodeList to determine if any elements were found.

    Here's an example:

    const elements = document.querySelectorAll('.non-existent-class');
    
    if (elements.length === 0) {
        console.log('No elements matched the selector.');
    } else {
        console.log(`${elements.length} elements matched the selector.`);
    }
    

    In this case, if there are no elements with the class .non-existent-class, the message "No elements matched the selector." will be logged to the console.

Related Questions: