How to distinguish between live and non-live NodeList collections?
Asked Answered
M

2

13

Both document.getElementsByTagName('div') and document.querySelectorAll('div') return NodeList collection. The only difference is that first method returns live-collection and second one - a static one.

The question is - is there any opportunity to distinguish one object from another only via inspecting these objects (i.e - not trying to add/remove some items to test "liveness")?

Milter answered 26/7, 2010 at 21:22 Comment(0)
K
6

The NodeList interface is agnostic of its dead or live status.

interface NodeList {
  Node item(in unsigned long index);
  readonly attribute unsigned long length;
};

It only contains a property length, and a method item so I'm afraid it's currently not possible to determine if an object is live without manipulating the DOM and seeing the effects.

Ketchum answered 27/7, 2010 at 17:21 Comment(8)
You're welcome, and a very interesting question. Is there a specific reason why you want to inspect the liveness of the object? If the reason is good and solves genuine problems, might as well propose it to the spec authors at w3.Ketchum
document.querySelectorAll returns a StaticNodeList, which by definition is not "live". Regardless of not being able to interrogate NodeList, I wonder if it's safe to assume NodeList, by convention, is always live.Geometrize
@Crescent - I didn't find a mention of StaticNodeList in Selectors API level 2 or in level 1, but it is only mentioned in a level 1 draft.Ketchum
@Anurag: you are right. It appeared as late as Dec 07 (w3.org/TR/2007/WD-selectors-api-20071221) but it looks like it has been replaced with NodeList as the return type.Geometrize
Still, the latest version states "The NodeList object returned by the querySelectorAll() method must be static, not live" - which is strange, since a NodeList is per se defined to be live.Southwestward
@Crescent - for example, in WebKit - document.querySelectorAll('div') instanceof NodeList is true, while trying to replace NodeList with StaticNodeList will cause an error - ReferenceError: Can't find variable: StaticNodeListMilter
@Ketchum - well, actually I'have no any practical reason, but I do believe that such basic properties should be possible to inspectMilter
@shabunc: yeah, that would be evidence of StaticNodeList being no more :( Note however that a host environment (eg a browser) is not required (by spec) to expose any top-level types within the global scope. Eg it is not required that NodeList be a valid name in the browser either!Geometrize
S
6
a=document.querySelectorAll('a');
b=document.getElementsByTagName('a');

a.toString() == "[object NodeList]"
b.toString() == "[object HTMLCollection]"

(in FF/Chrome)

Swen answered 11/3, 2011 at 5:40 Comment(1)
this is coincidental, not definitive. document.getElementsByName('link').toString() == "[object NodeList]" and it is liveMerited

© 2022 - 2024 — McMap. All rights reserved.