Friday, July 23, 2010

Inferring node placement via special sourceIndex values

I needed to know whether a node was in the DOM. Figuring there was a native property or method towards this end, I scoured Mozilla's documentation but could find nothing. Then Microsoft (yes, them) offered hope with Internet Explorer's sourceIndex property:
Retrieves the ordinal position of the object, in source order, as the object appears in the document's all collection.

Put simply, this proprietary property holds the numeric index of a node within the "all collection" - an IE construct reflecting everything in the browser DOM. Thus, I wondered what the index would be for nodes in memory; that is, a node not yet - or previously - appended to the DOM.

A quick test proved the sourceIndex property has special values for each scenario:

  • A value of -1 means the node has never been placed in the DOM.
  • A value of 0 means the node has been removed from the DOM.*

While the first case is pretty straight forward, the second (when 0) has an implied caveat. All array-like constructs are zero-based, and there is always a node at the zeroth index of document.all. Therefore, unless you know more about your node, a sourceIndex of 0 could be a false-positive and the node may still be in the DOM.

The generous folks at added my findings to their sourceIndex reference. Given their due diligence, I feel they've verified the application of my discovery.

I don't feel this proprietary property was intended as a node-placement indicator - hence the title of this blog entry. However, I've used it to great success as one, in a project where an IE only solution was needed (rare, I know).

Finally, for those interested in a cross browser solution, search to determine when a node is in the DOM.


No comments:

Post a Comment