return elements that match specified CSS selector(s)

What is the syntax for querySelectorAll() in JavaScript?

Answers:

  • The querySelectorAll() method in JavaScript is used to select all elements in the DOM that match a specified CSS selector. It returns a NodeList, which is a collection of the selected elements.

    Syntax:

    document.querySelectorAll(selector);
    

    Parameters:

    • selector: A string containing one or more CSS selectors separated by commas. This string specifies the elements to select.

    Example:

    // Select all <p> elements in the document
    const paragraphs = document.querySelectorAll('p');
    
    // Select all elements with the class "active"
    const activeElements = document.querySelectorAll('.active');
    
    // Select all <div> elements that are direct children of an element with the ID "container"
    const containerDivs = document.querySelectorAll('#container > div');
    
    // Select all elements matching multiple selectors
    const mixedElements = document.querySelectorAll('div.active, p.special');
    

    Usage:

    • The resulting NodeList can be iterated over using methods like forEach or by converting it to an array.
    • Note that the NodeList returned is "live" when using some methods but not when using querySelectorAll(). So the NodeList doesn't update if the document changes after the selection.

    Example with Iteration:

    const items = document.querySelectorAll('.item');
    
    items.forEach(item => {
      console.log(item.textContent); // Logs the text content of each item
    });
    

    In summary, querySelectorAll() is a powerful and flexible way to select multiple elements based on CSS selectors in JavaScript.

Related Questions: