I have an array of Elements 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.
I did find Node.compareDocumentPosition(), but it generates a bit mask of quite a few combinations, so not very ideal for a comparator.
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.
I don't necessarily agree that document.compareDocumentPosition() is insufficient for a comparator. Why do you consider this not ideal?
var elementArray = [];
elementArray.push(document.getElementById('div3'));
elementArray.push(document.getElementById('div2'));
elementArray.push(document.getElementById('div4'));
elementArray.push(document.getElementById('div1'));
function documentPositionComparator (a, b) {
  if (a === b) {
    return 0;
  }
  var position = a.compareDocumentPosition(b);
  if (position & Node.DOCUMENT_POSITION_FOLLOWING || position & Node.DOCUMENT_POSITION_CONTAINED_BY) {
    return -1;
  } else if (position & Node.DOCUMENT_POSITION_PRECEDING || position & Node.DOCUMENT_POSITION_CONTAINS) {
    return 1;
  } else {
    return 0;
  }
}
console.log('unsorted::', elementArray);
console.log('sorted::', elementArray.sort(documentPositionComparator));
<div id="div1">Div 1
  <div id="div2">Div 2
    <div id="div3">Div 3</div>
    <div id="div4">Div 4</div>
  </div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With