return elements that match specified CSS selector(s)

What types of selectors can I use with querySelectorAll()?

Answers:

  • The querySelectorAll() method in JavaScript allows you to select elements from the DOM using CSS-style selectors. Here are some types of selectors you can use:

    1. Type Selectors: Select elements by their tag name.

      document.querySelectorAll('div'); // selects all <div> elements
      
    2. Class Selectors: Select elements with a specific class.

      document.querySelectorAll('.my-class'); // selects all elements with class "my-class"
      
    3. ID Selectors: Select a unique element with a specific ID.

      document.querySelectorAll('#my-id'); // selects the element with ID "my-id"
      
    4. Attribute Selectors: Select elements based on their attributes.

      document.querySelectorAll('[type="text"]'); // selects all input elements with type="text"
      
    5. Descendant Selectors: Select elements that are descendants of a specified element.

      document.querySelectorAll('div p'); // selects all <p> elements that are inside <div> elements
      
    6. Child Selectors: Select elements that are direct children of a specified element.

      document.querySelectorAll('ul > li'); // selects all <li> elements that are direct children of <ul>
      
    7. Sibling Selectors: Select adjacent or general siblings of specified elements.

      document.querySelectorAll('h1 + p'); // selects the first <p> that follows an <h1>
      document.querySelectorAll('h1 ~ p'); // selects all <p> elements that follow an <h1>
      
    8. Pseudo-Classes: Select elements based on their state or position.

      document.querySelectorAll('a:hover'); // selects all <a> elements on hover (this works in CSS, but note that dynamic states won’t be directly captured in JS)
      document.querySelectorAll('li:nth-child(2)'); // selects the second <li> in any parent
      
    9. Pseudo-Elements: Select parts of elements, although querySelectorAll() does not directly select pseudo-elements, it can be used to target elements containing pseudo-elements defined in CSS.

      // While you cannot select pseudo-elements with querySelectorAll,
      // you can still select the parent elements.
      document.querySelectorAll('div::before'); // will not work directly
      
    10. Grouping Selectors: Combine multiple selectors using a comma.

      document.querySelectorAll('div, p, .my-class'); // selects all <div>, <p> elements, and elements with class "my-class"
      

    You can combine multiple selector types to create more specific queries. For instance:

    document.querySelectorAll('div.my-class > p#my-id');
    

    This would select <p> elements with specific class and ID that are direct children of a <div> with the class "my-class".

    Keep in mind that querySelectorAll() returns a NodeList, which can be iterated over, but it is not an actual Array unless you convert it.

Related Questions: