return elements that match specified CSS selector(s)

How can I combine different selectors in querySelectorAll()?

Answers:

  • You can combine different selectors in the querySelectorAll() method by using a comma to separate each selector within the string argument. This allows you to target multiple elements that match any of the specified selectors.

    Here’s how you can do it:

    // Combine different selectors
    const elements = document.querySelectorAll('.class1, .class2, #id1, div[attribute="value"]');
    
    // elements will contain all elements that are either .class1, .class2, #id1, or any div with a specific attribute.
    

    Example Breakdown:

    • '.class1' - selects all elements with the class class1.
    • '.class2' - selects all elements with the class class2.
    • '#id1' - selects the element with the ID id1.
    • 'div[attribute="value"]' - selects all <div> elements with a specific attribute equal to "value".

    Additional Notes:

    • You can use any valid CSS selectors, including combinations of classes, IDs, tag names, attributes, and pseudo-classes.
    • The resulting NodeList returned by querySelectorAll() can be iterated over, but it does not have array methods by default. If you need array methods, you can convert it to an array using Array.from() or the spread operator like so:
    const elementsArray = Array.from(elements); // or ...
    // const elementsArray = [...elements];
    

    Example Usage:

    const elements = document.querySelectorAll('.class1, .class2, #id1');
    elements.forEach(element => {
        console.log(element); // Perform actions with each selected element
    });
    

    Using querySelectorAll() with combined selectors is a powerful way to select multiple elements efficiently in your DOM manipulation.