jQuery.compare dom/compare

 

jQuery(el).compare([el])

jQuery.compare adds jQuery.fn.compare(element) which compares the position of two nodes and returns a number representing a bitmask detailing how they are positioned relative to each other.

$('#foo').compare($('#bar')) //-> Number

You can expect it to return the same results as | compareDocumentPosition. Parts of this documentation and source come from | John Resig.

The following list shows the bitmask, the number and what it corresponds to:

  • 000000 -> 0: Elements are identical
  • 000001 -> 1: The nodes are in different documents (or one is outside of a document)
  • 000010 -> 2: #bar precedes #foo
  • 000100 -> 4: #foo precedes #bar
  • 001000 -> 8: #bar contains #foo
  • 010000 -> 16: #foo contains #bar

The returned number can also represent a bitmask matching multiple conditions. For example, if the returned number is 20, which is the bitmask of 010100, it means that #foo precedes #bar and #foo contains #bar.

You can tests if the number returned by $.fn.compare matches any of these conditions by combining it with a bitwise AND operator:

if( $('#foo').compare($('#bar')) & 2 ) {
  console.log("#bar precedes #foo")
}

if( $('#foo').compare($('#bar')) & 8 ) {
  console.log("#bar contains #foo")
}

if( $('#foo').compare($('#bar')) & 10 ) {
  console.log("#bar precedes #foo and #bar contains #foo")
}

Demo