return elements that match specified CSS selector(s)

What is the syntax for using querySelectorAll with class selectors?

Answers:

  • The querySelectorAll method in JavaScript allows you to select multiple elements from the DOM using a CSS selector as a parameter. To use it with class selectors, you can follow this syntax:

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

    Here's a breakdown of the syntax:

    • document: This refers to the DOM document.
    • querySelectorAll: This method returns a NodeList of all elements that match the specified group of selectors.
    • '.your-class-name': This is the class selector. The dot (.) indicates that you are selecting by class. Replace your-class-name with the actual class name you want to select.

    Example:

    // Select all elements with the class 'example'
    const elements = document.querySelectorAll('.example');
    
    // Iterate over the NodeList and log each element
    elements.forEach(element => {
        console.log(element);
    });
    

    Notes:

    • You can use multiple class selectors as well: document.querySelectorAll('.class1.class2') will select elements that have both class1 and class2.
    • If you want to select elements that contain a certain class name but could have others as well, you still use the same syntax: document.querySelectorAll('.your-class-name').
    • The result will be a NodeList, which you can iterate over or convert to an array if needed.

Related Questions: