return elements that match specified CSS selector(s)

How does the NodeList from querySelectorAll() differ from an array?

Answers:

  • The NodeList returned by querySelectorAll() differs from a traditional JavaScript array in several key ways:

    1. Type:

      • NodeList is a collection of nodes (typically elements) retrieved from the DOM using methods like querySelectorAll().
      • In contrast, a regular array is an object that facilitates the storage and manipulation of a list of items.
    2. Methods and Properties:

      • NodeList does not have all the methods that arrays have. For example, it lacks methods like forEach(), map(), filter(), and other array manipulation methods until the introduction of the NodeList.prototype.forEach() method in modern browsers.
      • An array has several built-in methods for manipulation, iteration, and transformation.
    3. Iteration:

      • While you can use forEach() on a NodeList in modern browsers, traditional array iteration methods (like map or filter) are not available unless you convert the NodeList to an array first.
      • You can iterate a NodeList using a standard for loop or the for...of syntax in some environments.
    4. Dynamic vs. Static:

      • NodeList can be either "live" or "static." A live NodeList (like that from getElementsByTagName() or getElementsByClassName()) automatically updates when the DOM changes. However, querySelectorAll() returns a static NodeList that will not change as the DOM is altered after the call.
      • An array does not exhibit this live behavior and is a snapshot of the items provided at the time of creation.
    5. Length Property:

      • Both NodeList and arrays have a length property, but the length of a NodeList reflects the number of nodes it contains at the time it was created (for static NodeLists).
      • An array's length can be dynamically changed with methods like push() or pop().

    Converting NodeList to Array

    To convert a NodeList to an array, you can use methods like Array.from(), or the spread operator (...):

    const nodeList = document.querySelectorAll('div'); // NodeList
    const array = Array.from(nodeList); // Converts to Array
    // or
    const array2 = [...nodeList]; // Converts to Array using spread operator
    

    In summary, while NodeList and arrays may seem similar at a glance due to their indexing and length properties, they behave differently regarding methods and mutability.

Related Questions: