return elements that match specified CSS selector(s)

Can querySelectorAll() select multiple elements at once?

Answers:

  • Yes, querySelectorAll() can be used to select multiple elements at once. It allows you to use CSS selectors to match multiple elements in the DOM.

    When you call querySelectorAll(selector), it returns a NodeList of all elements that match the specified CSS selector. For example, you can use it like this:

    // Select all <div> elements
    let divs = document.querySelectorAll('div');
    
    // Select multiple elements with different types
    let elements = document.querySelectorAll('div, p, span'); // selects all <div>, <p>, and <span> elements
    

    The result is a static NodeList containing all the matched elements, which you can then iterate over or manipulate as needed. Keep in mind that the returned NodeList is not an array, so if you need array methods, you'll have to convert it to an array using methods like Array.from() or the spread operator ([...]).

    Here's an example of iterating over the selected elements:

    let divs = document.querySelectorAll('div');
    divs.forEach(div => {
        console.log(div.textContent); // Logs text content of each <div>
    });
    

Related Questions: