0

The docs say that document.querySelector return an Element while document.querySelectorAll returns a NodeList. Why is this discrepancy there? Why document.querySelectorAll return an Element array?

Note: The question tagged as duplicate of this isn't answering my question that why document.querySelectorAll does not return an Element array? on the same lines as document.querySelector return an `Element. The former is just plural of the latter.

Daud
  • 7,429
  • 18
  • 68
  • 115
  • 1
    Does this answer your question? [Difference between HTMLCollection, NodeLists, and arrays of objects](https://stackoverflow.com/questions/15763358/difference-between-htmlcollection-nodelists-and-arrays-of-objects) – Álvaro Tihanyi May 30 '21 at 11:49
  • If you only need or expect one why would you need a collection? Answer seems fairly obvious here – charlietfl May 30 '21 at 12:43
  • Are you asking about the discrepancy between `Node` and `Element`, or [the discrepancy between single values and lists](https://stackoverflow.com/q/10693845/1048572)? – Bergi May 30 '21 at 12:44
  • I was trying to understand why an `Element` array isn't returned in the case of `querySelectorAll`, which would have been in line with the output of `querySelector`. I have updated the question to reflect that – Daud May 30 '21 at 15:54
  • @ÁlvaroTihanyi No. It doesn't answer my question. Have updated the question to make it even more clear – Daud May 30 '21 at 16:20

1 Answers1

3

For document.querySelectorAll(), on MDN, it says this:

[it] returns a static (not live) NodeList representing a list of the document's elements

So, the NodeList does contain a list of elements. The reason why this particular data structure is called a "NodeList" and not just an "ElementList" is because it can contain other types of nodes besides elements (such as a comment node, a text node, or a fragement node). document.querySelectorAll() will only return a NodeList with elements in it, but other functions/properties (such as the .childNodes property) may generate nodeLists with other types of nodes.

One special property a nodeList has, that an array does not, is that a nodeList can be "live", which means it'll auto-update when there are changes to the DOM. This, however, does not apply to document.querySelectorAll() as querySelectorAll() will always return a non-live nodeList. As far as I can tell, they could have simply returned an element array instead, but maybe chose to return a nodeList in order to keep their browser APIs consistent with each other. Perhaps there's certain hidden optimizations they're able to do with the nodeList data structure.

Scotty Jamison
  • 10,498
  • 2
  • 24
  • 30