return elements that match specified CSS selector(s)

What types of selectors can be used with querySelectorAll()?

Answers:

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

    1. Type Selector: Selects elements by their tag name.

      • Example: document.querySelectorAll('div') selects all <div> elements.
    2. Class Selector: Selects elements by their class name.

      • Example: document.querySelectorAll('.my-class') selects all elements with the class my-class.
    3. ID Selector: Selects a single element by its ID.

      • Example: document.querySelectorAll('#my-id') selects the element with the ID my-id. Note that IDs should be unique within a document, so this will return a NodeList with at most one element.
    4. Attribute Selector: Selects elements based on their attributes.

      • Example: document.querySelectorAll('[data-attribute]') selects all elements with a data-attribute attribute.
    5. Descendant Selector: Selects elements that are descendants of a specified element.

      • Example: document.querySelectorAll('div p') selects all <p> elements that are within <div> elements.
    6. Child Selector: Selects elements that are direct children of a specified element.

      • Example: document.querySelectorAll('div > p') selects all <p> elements that are direct children of a <div>.
    7. Sibling Selector:

      • Adjacent sibling selector (+): Selects the next sibling element.
        • Example: document.querySelectorAll('h1 + p') selects the first <p> that follows any <h1>.
      • General sibling selector (~): Selects all sibling elements that follow.
        • Example: document.querySelectorAll('h1 ~ p') selects all <p> siblings that follow any <h1>.
    8. Pseudo-classes: Selects elements based on their state or position.

      • Example: document.querySelectorAll('li:first-child') selects the first <li> in a list.
    9. Pseudo-elements: Selects a specified part of an element (Note: these cannot be selected with querySelectorAll() as they don't correspond to actual DOM nodes).

      • Example: ::before or ::after are used in CSS but not applicable here.
    10. Combinators: Used to combine selectors.

    • Example: document.querySelectorAll('div .my-class') selects elements with class my-class that are descendants of any <div>.

    These selectors can be combined to create more complex selections. For example: document.querySelectorAll('div.my-class > p:first-child') selects the first <p> child of any <div> that has the class my-class.

    Using this versatility, you can effectively and efficiently target specific elements in the DOM for manipulation or styling.

Related Questions: