return elements that match specified CSS selector(s)

How do you check if the result of querySelectorAll() is empty?

Answers:

  • In JavaScript, when you use querySelectorAll(), it returns a NodeList of elements that match the specified CSS selector. If no elements match, the NodeList will be empty, but it is important to note that an empty NodeList is still an object. To check if it is empty, you can use the length property of the returned NodeList.

    Here’s how you can check if the result of querySelectorAll() is empty:

    const elements = document.querySelectorAll('your-selector-here');
    
    if (elements.length === 0) {
        console.log('No elements found');
    } else {
        console.log('Elements found:', elements);
    }
    

    Replace 'your-selector-here' with the CSS selector you want to use. If elements.length is 0, it means that no elements matched your query, and hence the result is considered empty.