return elements that match specified CSS selector(s)

Can querySelectorAll() be used with classes and IDs?

Answers:

  • Yes, the querySelectorAll() method in JavaScript can be used to select elements based on their classes and IDs, as well as other selectors defined in CSS.

    Using Classes

    When selecting elements by class name, you prefix the class with a dot (.). For example, to select all elements with the class example-class, you can use:

    const elements = document.querySelectorAll('.example-class');
    

    Using IDs

    When selecting elements by ID, you prefix the ID with a hash (#). For example, to select an element with the ID example-id, you can use:

    const element = document.querySelectorAll('#example-id');
    

    Selecting Both Classes and IDs

    You can also combine selectors. For example, to select all elements with the class example-class that are within an element with the ID example-id, you can do:

    const elements = document.querySelectorAll('#example-id .example-class');
    

    Summary

    • Use . for classes.
    • Use # for IDs.
    • Combine selectors as needed to target specific elements.

    querySelectorAll() returns a NodeList containing all the matches, and you can iterate through it or convert it into an array if needed.

Related Questions: