return elements that match specified CSS selector(s)

Can querySelectorAll() select multiple elements in a single call?

Answers:

  • Yes, querySelectorAll() can select multiple elements in a single call. You can pass a CSS selector string that includes multiple selectors to querySelectorAll(), and it will return a NodeList containing all elements that match any of the specified selectors.

    For example:

    const elements = document.querySelectorAll('div, .my-class, #my-id');
    

    In this example, querySelectorAll will select:

    • All <div> elements
    • All elements with the class my-class
    • The element with the id my-id

    The resulting elements variable will contain a NodeList of all matching elements. You can then iterate over this NodeList or convert it to an array if needed. Note that the elements are returned in the order they appear in the document.

Related Questions: