return elements that match specified CSS selector(s)

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

Answers:

  • The querySelectorAll() method in JavaScript allows you to select multiple elements from the DOM using CSS selectors. Here's a breakdown of the types of selectors you can use:

    1. Basic Selectors:

      • Type Selector: Selects elements by their tag name (e.g., div, p).

        document.querySelectorAll('div');
        
      • Class Selector: Selects elements that have a specific class (e.g., .my-class).

        document.querySelectorAll('.my-class');
        
      • ID Selector: Selects an element with a specific ID (e.g., #my-id). Note that IDs are unique.

        document.querySelectorAll('#my-id');
        
    2. Attribute Selectors:

      • You can select elements based on the presence or value of attributes.
        document.querySelectorAll('[attr]'); // Selects elements with the specified attribute
        document.querySelectorAll('[attr="value"]'); // Selects elements with the specified attribute value
        
    3. Pseudo-classes:

      • Selects elements based on their state or position.
        document.querySelectorAll(':hover'); // Selects elements being hovered
        document.querySelectorAll(':first-child'); // Selects the first child of its parent
        document.querySelectorAll(':last-child'); // Selects the last child of its parent
        
    4. Pseudo-elements:

      • Used to style specific parts of an element.
        document.querySelectorAll('p::first-line'); // Selects the first line of each paragraph
        
    5. Combinators:

      • You can combine selectors to narrow down your selection.

      • Descendant Selector: Selects elements that are inside a specified element (e.g., div p).

        document.querySelectorAll('div p'); // Selects all <p> elements within <div>
        
      • Child Selector: Selects elements that are direct children of a specified element (e.g., div > p).

        document.querySelectorAll('div > p'); // Selects <p> elements that are direct children of <div>
        
      • Adjacent Sibling Selector: Selects an element that is directly next to another (e.g., h1 + p).

        document.querySelectorAll('h1 + p'); // Selects the first <p> that is immediately after an <h1>
        
      • General Sibling Selector: Selects all siblings after a specified element (e.g., h1 ~ p).

        document.querySelectorAll('h1 ~ p'); // Selects all <p> elements after an <h1>
        

    These selectors give you powerful tools to target specific elements in the DOM, making it easier to manipulate them with JavaScript. Remember that querySelectorAll() returns a NodeList, which can be iterated over but is not an array.

Related Questions: