return elements that match specified CSS selector(s)

How do I select multiple classes using querySelectorAll?

Answers:

  • You can use querySelectorAll to select multiple classes in JavaScript by combining the class selectors with a comma. Each class selector should be prefixed with a period (.). Here's how you can do it:

    Example

    If you want to select elements that have either the class class1 or class2, you would write:

    const elements = document.querySelectorAll('.class1, .class2');
    

    Explanation

    • The . indicates that you are selecting a class.
    • Multiple class selectors are separated by commas.
    • The querySelectorAll method returns a NodeList containing all elements that match any of the selectors provided.

    Using the Selected Elements

    You can then loop through the NodeList to do something with each selected element:

    elements.forEach(element => {
        // Perform an action with each element
        console.log(element);
    });
    

    Additional Notes

    • You can combine multiple classes in a single expression if you want to select only elements that have all of those classes. For example:
    const specificElements = document.querySelectorAll('.class1.class2');
    

    This selects elements that have both class1 and class2.

    • Remember to ensure that your selectors accurately reflect the classes you want to select, adjusting for the presence of spaces if necessary. For instance, if you want to select an element that has both classes (and no other classes), do it as shown above.

Related Questions: