Skip to content

Instantly share code, notes, and snippets.

@tmpvar
Forked from bmeck/compareDocumentPosition.js
Created October 8, 2010 04:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmpvar/616379 to your computer and use it in GitHub Desktop.
Save tmpvar/616379 to your computer and use it in GitHub Desktop.
//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