Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort elements by document order in JavaScript

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.

like image 466
billc.cn Avatar asked Aug 13 '15 14:08

billc.cn


1 Answers

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>
like image 174
Palpatim Avatar answered Oct 18 '22 20:10

Palpatim