title: Sort elements by document order in JavaScript
body: <p>I have an array of <code>Element</code>s and I want them in document order. I know this is trivial to achieve in XPath, but the logic I have to implement is a bit complicated for a single expression.</p>
  
  <p>I did find <code>Node.compareDocumentPosition()</code>, but it generates a bit mask of quite a few combinations, so not very ideal for a comparator.</p>
  
  <p>As I final resort, I could probably add a random attribute on to all the elements in the array and select them again using XPath, but I'd rather not do that if possible.</p>