return elements that match specified CSS selector(s)

Can I use querySelectorAll() to select elements by class name?

Answers:

  • Yes, you can use querySelectorAll() to select elements by class name. To do this, you would use the class selector syntax, which is a dot (.) followed by the class name.

    For example, if you have several elements with a class name of my-class, you can select all of these elements as follows:

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

    The elements variable will contain a NodeList of all matching elements. You can then iterate over this NodeList using methods like forEach() or convert it to an array if you want to use array methods.

    Here’s a simple example:

    // Assuming there are multiple elements with the class name "my-class"
    const elements = document.querySelectorAll('.my-class');
    elements.forEach(element => {
        console.log(element.textContent); // Logs the text content of each element
    });
    

    This approach allows you to select any elements in the DOM that have the specified class name efficiently.

Related Questions: