Daud
Daud

Reputation: 7877

Why does document.querySelector return an Element while document.querySelectorAll returns a NodeList

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.

Upvotes: -1

Views: 1264

Answers (1)

Scotty Jamison
Scotty Jamison

Reputation: 13129

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.

Upvotes: 3

Related Questions