return elements that match specified CSS selector(s)

Can querySelectorAll return an empty NodeList?

Answers:

  • Yes, querySelectorAll can return an empty NodeList. This occurs when the specified CSS selector does not match any elements in the document.

    For example, if you run the following code:

    const elements = document.querySelectorAll('.non-existent-class');
    console.log(elements); // This will log an empty NodeList
    

    In this case, since there are no elements with the class non-existent-class, elements will be an empty NodeList. It's important to note that an empty NodeList is still an instance of the NodeList interface and has a length property of 0:

    console.log(elements.length); // Outputs: 0
    

    You can safely iterate over this empty NodeList without generating any errors.

Related Questions: