Skip to content

Instantly share code, notes, and snippets.

@loilo
Last active February 2, 2020 09:21
Show Gist options
  • Select an option

  • Save loilo/4ffc3de13d14539a23d8 to your computer and use it in GitHub Desktop.

Select an option

Save loilo/4ffc3de13d14539a23d8 to your computer and use it in GitHub Desktop.
Compares the position of two elements in a DOM tree and returns -1, 0 or 1
// Note: This code is obsolete. There's a cross-browser DOM method `compareDocumentPosition()` which does the same, but more detailed.
// See https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition
function compareNodePosition( nodeA, nodeB, container ) {
if ( !( container instanceof HTMLElement ) ) {
container = document.body;
}
function getNodePositionArray( el, container ) {
var arr = [];
var parentNode = el;
while ( parentNode !== container ) {
arr.unshift( Array.from( parentNode.parentNode.childNodes ).indexOf( parentNode ) );
parentNode = parentNode.parentNode;
if ( parentNode === null ) {
throw {
message: "Could not find node in given container",
node: el,
container: container
};
}
}
return arr;
}
function comparePositionArray( a, b ) {
if ( a.length === 0 && b.length === 0 ) {
return 0;
} else if ( a.length === 0 ) {
return 1;
} else if ( b.length === 0 ) {
return -1;
} else {
if ( a[ 0 ] === b[ 0 ] ) {
a.shift();
b.shift();
return comparePositionArray( a, b );
} else if ( a[ 0 ] < b[ 0 ] ) {
return -1;
} else {
return 1;
}
}
}
return comparePositionArray( getNodePositionArray( nodeA, container ), getNodePositionArray( nodeB, container ) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment