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 DOM elements using CSS-style selectors. Here are the types of selectors you can use:

    1. Element Selectors: Selects all elements of a specific type.

      • Example: document.querySelectorAll('div') selects all <div> elements.
    2. Class Selectors: Selects all elements with a specific class.

      • Example: document.querySelectorAll('.my-class') selects all elements with the class my-class.
    3. ID Selectors: Selects an element with a specific ID (note: IDs should be unique within a document).

      • Example: document.querySelectorAll('#my-id') selects the element with the ID my-id.
    4. Attribute Selectors: Selects elements based on their attributes.

      • Example: document.querySelectorAll('[href]') selects all elements with an href attribute.
    5. Pseudo-class Selectors: Selects elements based on their state or position.

      • Example: document.querySelectorAll(':hover') selects elements that are currently being hovered over.
    6. Pseudo-element Selectors: Selects part of an element.

      • Example: document.querySelectorAll('p::first-line') selects the first line of <p> elements.
    7. Descendant Selectors: Selects elements that are descendants of a specified element.

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

      • Example: document.querySelectorAll('ul > li') selects all <li> elements that are direct children of a <ul>.
    9. Sibling Selectors: Selects elements that are siblings of a specified element.

      • Example: document.querySelectorAll('h2 + p') selects the first <p> element that comes immediately after each <h2>.
    10. Group Selectors: You can combine selectors to select multiple elements.

      • Example: document.querySelectorAll('div, p, .my-class') selects all <div>, all <p>, and all elements with class my-class.

    With these selectors, you can create complex queries to select DOM elements efficiently based on their attributes, classes, or hierarchy within the document structure.

Related Questions: