Skip to content

Instantly share code, notes, and snippets.

@krusynth
Created September 10, 2014 20:24
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 krusynth/6cd3c06a99ce34197880 to your computer and use it in GitHub Desktop.
Save krusynth/6cd3c06a99ce34197880 to your computer and use it in GitHub Desktop.
Polyfill for compareDocumentPosition if you need that for old IE or something. But you could probably just use .contains() too.
function compareDocumentPosition(thisNode, other) {
function recursivelyWalk(nodes, cb) {
for (var i = 0, len = nodes.length; i < len; i++) {
var node = nodes[i];
var ret = cb(node);
if (ret) {
return ret;
}
if (node.childNodes && node.childNodes.length) {
var ret = recursivelyWalk(node.childNodes, cb);
if (ret) {
return ret;
}
}
}
}
function testNodeForComparePosition(node, other) {
if (node === other) {
return true;
}
}
function simpleCompare(node, other) {
// Check to see if any of other's parents
// are the node we're checking.
if(node.nodeType == Node.ELEMENT_NODE) {
while (other = other.parentNode) {
if(other === node) {
return Node.DOCUMENT_POSITION_CONTAINED_BY +
Node.DOCUMENT_POSITION_FOLLOWING;
}
}
}
// And the reverse.
else if(other.nodeType == Node.ELEMENT_NODE) {
while (node = node.parentNode) {
if(other === node) {
return Node.DOCUMENT_POSITION_CONTAINS +
Node.DOCUMENT_POSITION_PRECEDING
}
}
}
}
function identifyWhichIsFirst(node) {
if (node === other) {
return "other";
} else if (node === reference) {
return "reference";
}
}
var reference = thisNode,
referenceTop = thisNode,
otherTop = other;
if (this === other) {
return 0;
}
while (referenceTop.parentNode) {
referenceTop = referenceTop.parentNode;
}
while (otherTop.parentNode) {
otherTop = otherTop.parentNode;
}
if (referenceTop !== otherTop) {
return Node.DOCUMENT_POSITION_DISCONNECTED;
}
result = simpleCompare(thisNode, other);
if(result) {
return result;
}
var ret = recursivelyWalk(
[referenceTop],
identifyWhichIsFirst
);
if (ret === "other") {
return Node.DOCUMENT_POSITION_PRECEDING;
} else {
return Node.DOCUMENT_POSITION_FOLLOWING;
}
}
@cyberhck
Copy link

No, we can't use .contains, because I've to create a .contains polyfill and my code looks like this:

// This polyfill only works in IE9+
if(!Element.prototype.contains){
    Element.prototype.contains = function(node){
        return !!(this.compareDocumentPosition(node) & 16);
    };
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment