return elements that match specified CSS selector(s)

What is the purpose of querySelectorAll() in JavaScript?

Answers:

  • The querySelectorAll() method in JavaScript is used to select multiple elements from a DOM (Document Object Model) based on a specified CSS selector. It returns a static (non-live) NodeList of all elements matching the specified selector(s).

    Key Points about querySelectorAll():

    1. Syntax:

      const elements = document.querySelectorAll(selector);
      
      • selector: A string that contains one or more CSS selectors separated by commas.
    2. Returns a NodeList:

      • The method returns a NodeList, which is similar to an array but lacks some array methods. However, you can convert it into an array using methods like Array.from() or the spread operator ([...]).
    3. Static NodeList:

      • The NodeList returned is static, meaning it does not change if the document changes after the query is made. If elements that match the criteria are added or removed from the DOM later, the NodeList will not automatically update.
    4. Bootstrap Selector Capabilities:

      • You can use complex CSS selectors, such as class selectors (.class-name), ID selectors (#id-name), attribute selectors ([attribute=value]), pseudo-classes (:hover), and more.
    5. Browser Compatibility:

      • Supported in all modern browsers. Be sure to check for compatibility if you are supporting very old browsers.

    Example Usage:

    Selecting all elements with a specific class:

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

    Selecting multiple different elements:

    const elements = document.querySelectorAll('div, p, .class-name');
    elements.forEach(element => {
        console.log(element.tagName); // Logs the tag name of each selected element
    });
    

    Overall, querySelectorAll() is a powerful and flexible method that allows developers to easily select elements from the DOM using modern JavaScript and CSS selectors.

Related Questions: