return elements that match specified CSS selector(s)

Can you select elements with querySelectorAll() by class name or ID?

Answers:

  • Yes, you can use querySelectorAll() to select elements by class name or ID in JavaScript.

    • To select elements by class name, you can use a dot (.) followed by the class name. For example:
    const elementsByClass = document.querySelectorAll('.my-class');
    
    • To select an element by ID, you can use a hash (#) followed by the ID name. For example:
    const elementById = document.querySelectorAll('#my-id');
    

    Note that when selecting by ID with querySelectorAll(), it will return a NodeList containing the element(s) matching that ID. Since IDs are meant to be unique within a document, you typically only expect one element, but it's still considered best practice to use querySelector() for selecting a single element by ID:

    const singleElementById = document.querySelector('#my-id');
    

    In summary, querySelectorAll() can be used for both class names and IDs, but remember to select a single ID with querySelector() for better clarity and performance.