return elements that match specified CSS selector(s)

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

Answers:

  • The querySelectorAll() method allows you to select elements in the DOM using CSS selectors. It accepts a string parameter that specifies a group of CSS selectors, and will return all elements that match any of those selectors. Here are some types of selectors you can use with querySelectorAll():

    1. Universal Selector:

      • *: Selects all elements.
      const allElements = document.querySelectorAll('*');
      
    2. Type Selector:

      • element: Selects all elements of a specific type (tag name).
      const divs = document.querySelectorAll('div');
      
    3. Class Selector:

      • .className: Selects all elements with a specific class.
      const items = document.querySelectorAll('.my-class');
      
    4. ID Selector:

      • #idName: Selects an element with a specific ID (note that IDs should be unique).
      const header = document.querySelectorAll('#my-id');
      
    5. Attribute Selector:

      • [attribute]: Selects elements with a specific attribute.
      • [attribute="value"]: Selects elements with a specific attribute value.
      const inputs = document.querySelectorAll('input[type="text"]');
      
    6. Descendant Selector:

      • ancestor descendant: Selects elements that are descendants of a specified ancestor.
      const listItems = document.querySelectorAll('ul li');
      
    7. Child Selector:

      • parent > child: Selects elements that are direct children of a specified parent.
      const directChildren = document.querySelectorAll('div > p');
      
    8. Adjacent Sibling Selector:

      • previous + next: Selects an element that is directly after a specified element.
      const nextElement = document.querySelectorAll('h1 + p');
      
    9. General Sibling Selector:

      • previous ~ siblings: Selects all siblings of a specified element.
      const siblings = document.querySelectorAll('h1 ~ p');
      
    10. Pseudo-classes:

      • :hover, :nth-child(n), :last-child, etc.
      const secondItems = document.querySelectorAll('li:nth-child(2)');
      
    11. Pseudo-elements:

      • ::before, ::after, etc. (Note: pseudo-elements might not work as expected with querySelectorAll()).
      const beforeElement = document.querySelectorAll('p::before'); // Usually doesn't work directly
      

    You can also combine selectors and use groups with commas:

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

    These selectors allow for flexible and powerful ways to traverse and manipulate the DOM based on specific criteria.