compareDocumentPosition function

int compareDocumentPosition(
  1. Node a,
  2. Node b
)

A Comparator for sorting Nodes based on document order.

Example:

// [elements] is a List<Element>.
elements.sort(compareDocumentPosition);
// Now they're sorted according to their position in the document.

Implementation

int compareDocumentPosition(Node a, Node b) {
  int bitmask = js_util.callMethod(a, 'compareDocumentPosition', [b]);
  if ((bitmask & 4) != 0 || (bitmask & 16) != 0) {
    // DOCUMENT_POSITION_FOLLOWING or DOCUMENT_POSITION_CONTAINED_BY
    return -1;
  } else if ((bitmask & 2) != 0 || (bitmask & 8) != 0) {
    // DOCUMENT_POSITION_PRECEDING or DOCUMENT_POSITION_CONTAINS
    return 1;
  } else {
    return 0;
  }
}