querySelectorAll() the best JavaScript function in the world!

How does the querySelectorAll() function work?

1 answer

  1. The querySelectorAll() function is a method in the Document Object Model (DOM) that allows you to select and return a list of elements that match a specified group of selectors. It returns a NodeList, which is a collection of elements that match the given CSS selectors.

    Here's how the querySelectorAll() function works:

    1. Include the method in your JavaScript code and pass your desired CSS selector(s) as a parameter in the form of a string.
    2. The function searches through the entire DOM tree to find elements that match the given selectors. Selectors can include class names, tag names, IDs, or any valid CSS selector.
    3. The elements that match the given selectors are collected and returned as a NodeList.
    4. You can then manipulate, modify, or extract information from the returned elements using different DOM methods and properties.

    Here's an example of how to use querySelectorAll():

    <!DOCTYPE html>
    .my-class {
    color: red;
    <p class="my-class">This is paragraph 1 with 'my-class' class.</p>
    <p class="my-class">This is paragraph 2 with 'my-class' class.</p>
    <p>This is paragraph 3 without the class.</p>

    // Select all elements with the class "my-class"
    const elements = document.querySelectorAll(".my-class");

    // Loop through the NodeList and modify the text content
    elements.forEach(element => {
    element.textContent = "This element has the 'my-class' class.";

    In the example above, the querySelectorAll() function selects all the elements with the class `my-class` and modifies their text content. The NodeList returned in this case contains two `p` elements.