Created
October 8, 2010 04:41
-
-
Save bmeck/616369 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Attach me to Node.prototype as well | |
var DOCUMENT_POSITION_DISCONNECTED = Node.prototype.DOCUMENT_POSITION_DISCONNECTED = 0x01 | |
var DOCUMENT_POSITION_PRECEDING = Node.prototype.DOCUMENT_POSITION_PRECEDING = 0x02 | |
var DOCUMENT_POSITION_FOLLOWING = Node.prototype.DOCUMENT_POSITION_FOLLOWING = 0x04 | |
var DOCUMENT_POSITION_CONTAINS = Node.prototype.DOCUMENT_POSITION_CONTAINS = 0x08 | |
var DOCUMENT_POSITION_CONTAINED_BY = Node.prototype.DOCUMENT_POSITION_CONTAINED_BY = 0x10 | |
Node.prototype.compareDocumentPosition = function compareDocumentPosition( otherNode ) { | |
if( !(otherNode instanceof Node) ) { | |
throw Error("Comparing position against non-Node values is not allowed") | |
} | |
if( this === otherNode ) return 0 | |
if( this.ownerDocument !== otherNode.ownerDocument ) { | |
return DOCUMENT_POSITION_DISCONNECTED | |
} | |
var point = this | |
var parents = [ ] | |
while( point ) { | |
if( point == otherNode ) return DOCUMENT_POSITION_CONTAINS | |
parents.push( point ) | |
point = point.parentNode | |
} | |
point = otherNode | |
while( point ) { | |
if( point == this ) return DOCUMENT_POSITION_CONTAINED_BY | |
var location_index = parents.indexOf( point ) | |
if( location_index !== -1) { | |
var smallest_common_ancestor = parents[ location_index ] | |
var this_index = smallest_common_ancestor.childNodes.indexOf( this ) | |
var other_index = smallest_common_ancestor.childNodes.indexOf( otherNode ) | |
if( this_index > other_index ) { | |
return DOCUMENT_POSITION_PRECEDING | |
} | |
else { | |
return DOCUMENT_POSITION_FOLLOWING | |
} | |
} | |
point = point.parentNode | |
} | |
return DOCUMENT_POSITION_DISCONNECTED | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment