Skip to content

Instantly share code, notes, and snippets.

@Justineo
Last active August 29, 2015 14:07
Show Gist options
  • Save Justineo/ec7275cda82e986fc47b to your computer and use it in GitHub Desktop.
Save Justineo/ec7275cda82e986fc47b to your computer and use it in GitHub Desktop.
Sort Nodes
// sort an array of DOM nodes according to the HTML tree order
// http://www.w3.org/TR/html5/infrastructure.html#tree-order
function sortNodes(nodes) {
nodes.sort(function (a, b) {
var posCompare = a.compareDocumentPosition(b);
if (posCompare & 4 || posCompare & 16) {
// a < b
return -1;
} else if (posCompare & 2 || posCompare & 8) {
// a > b
return 1;
} else if (posCompare & 1 || posCompare & 32) {
throw 'Cannot sort the given nodes.';
} else {
return 0;
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment