return elements that match specified CSS selector(s)

Can I use querySelectorAll to filter elements by multiple class names?

Answers:

  • Yes, you can use querySelectorAll to select elements by multiple class names in a single selector. The syntax for this involves combining class selectors with a dot (.) for each class you want to match.

    For example, if you want to select all elements that have both class1 and class2, you would use the following syntax:

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

    Here, the querySelectorAll method will return a NodeList of all elements that have both class1 and class2 applied to them.

    If you want to select elements that have either class (i.e., a logical "OR"), you would separate the class selectors with a comma:

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

    This will return a NodeList of all elements that have either class1 or class2.

    Remember, the selectors are case-sensitive and should follow the CSS selector rules.