return elements that match specified CSS selector(s)

What are the return types of querySelector() and querySelectorAll()?

Answers:

  • The querySelector() and querySelectorAll() methods in the DOM return different types of values:

    1. querySelector():

      • Return Type: It returns the first element within the document that matches the specified CSS selector(s). If no matching elements are found, it returns null.
      • Example:
        const element = document.querySelector('.my-class');
        // element will be the first element with the class 'my-class' or null if no such element exists.
        
    2. querySelectorAll():

      • Return Type: It returns a NodeList containing all the elements within the document that match the specified CSS selector(s). If no matching elements are found, it returns an empty NodeList.
      • Example:
        const elements = document.querySelectorAll('.my-class');
        // elements will be a NodeList of all elements with the class 'my-class', or an empty NodeList if none are found.
        

    In summary:

    • querySelector() returns a single element or null.
    • querySelectorAll() returns a NodeList, which can be empty but never null.

Related Questions: