Friday, October 23, 2009

Node sourceIndex for every browser

I was doing a couple of tests in my bloody Android and I don't even know how I ended up with such snippet ... anyway, accordingly with @ppk table sourceIndex is a node property compatible with every version of Internet Explorer and latest Opera browser but not with Chrome, Firefox, or Safari (WebKit Android and iPhone as well).

Being these unsupported browsers compatible with both native Array.prototype.indexOf and __defineGetter__ and being 5 to 100 times faster than IE, I thought: why don't put this as well into vice-versa?

/** sourceIndex by vice-versa - Mit Style License
* @target FireFox, Safari, Chrome
*/
if(typeof document.documentElement.sourceIndex == "undefined")
HTMLElement.prototype.__defineGetter__("sourceIndex", (function(indexOf){
return function sourceIndex(){
return indexOf.call(this.ownerDocument.getElementsByTagName("*"), this);
};
})(Array.prototype.indexOf));
;

I so much would have cached the live getElementsByTagName("*") object then I thought there must be a reason if different libraries pass via node.ownerDocument rather than direct document ... isn't it? Well, if not I'll change soon but right now I am pretty much happy with performances :)

Why sourceIndex


If we would like to know, as example, if a node is before or after another one (considering that nested nodes will be considered always after their container) I bet there's nothing simpler than:

if(a.sourceIndex < b.sourceIndex){
// move up b, move down a
} else {
// move up a, move down b
}

... or something similar, enjoy

Update
Apparently in jQuery dev list somebody already talked about analogue snippets (thanks @diegoperini) but it's not my idea to normalize anything, respecting what sourceIndex should do: compare index in the full HTMLCollection and nothing else, the rest could be easily implemented over this snippet :)

No comments:

Post a Comment