return elements that match specified CSS selector(s)

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

Answers:

  • When you use querySelectorAll() and no elements match the specified selector, the method returns an empty NodeList. This NodeList is a read-only list of nodes that matches the selector.

    Here’s a brief summary of what happens:

    • Return Value: An empty NodeList, which is an iterable collection that can be traversed using loops.
    • Length Property: The length property of the returned NodeList will be 0.
    • Usage: You can check the length of the NodeList to determine if any elements were found.

    Here's an example:

    let elements = document.querySelectorAll('.non-existent-class');
    
    console.log(elements.length); // Outputs: 0
    
    if (elements.length === 0) {
        console.log('No elements found matching the selector.');
    } else {
        console.log('Elements found:', elements);
    }
    

    In this example, since there are no elements with the class 'non-existent-class', the NodeList returned will be empty, and the length will be 0, triggering the corresponding message in the console.

Related Questions: