return elements that match specified CSS selector(s)

How do I filter elements by class name using querySelectorAll?

Answers:

  • To filter elements by class name using querySelectorAll, you can use the class name directly in your CSS selector string. Here's how you can do it:

    Syntax

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

    Example

    Suppose you have the following HTML:

    <div class="box"></div>
    <div class="box highlighted"></div>
    <div class="circle"></div>
    <div class="box"></div>
    

    If you want to select all elements that have the class name box, you can use:

    const boxes = document.querySelectorAll('.box');
    

    Usage

    boxes will be a NodeList containing all elements with the class box. You can then loop through this NodeList and manipulate the elements as needed.

    Looping through NodeList

    Here’s an example of looping through the selected elements:

    boxes.forEach(box => {
        // Do something with each box element
        box.style.backgroundColor = 'blue'; // Change the background of each box to blue
    });
    

    Additional Filtering

    If you want to further filter elements with multiple classes or specific attributes, you can combine multiple selectors. For example, if you want to select only boxes that also have the class highlighted, you can do:

    const highlightedBoxes = document.querySelectorAll('.box.highlighted');
    

    This will return only the elements that have both the box and highlighted classes.

    Conclusion

    Using querySelectorAll with class names is straightforward. Just remember to prefix the class name with a dot (.) and you can easily filter the elements you need.

Related Questions: