Last active
August 29, 2015 14:07
-
-
Save Justineo/ec7275cda82e986fc47b to your computer and use it in GitHub Desktop.
Sort Nodes
This file contains 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
// 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