cross browser compare document position

AlbanianGhost

New Member
DOM4 compareDocumentPositionI want to implement compareDocumentPosition. Resig has made a great start at doing just this. I've taken his code and neatened it up\[code\]function compareDocumentPosition(other) { var ret = 0; if (this.contains) { if (this !== other && this.contains(other)) { ret += 16; } if (this !== other && other.contains(this)) { ret += 8; } if (this.sourceIndex >= 0 && other.sourceIndex >= 0) { if (this.sourceIndex < other.sourceIndex) { ret += 4; } if (this.sourceIndex > other.sourceIndex) { ret += 2; } } else { ret += 1; } } return ret;}\[/code\]This works for \[code\]Element\[/code\] but does not for \[code\]Text\[/code\] or \[code\]DocumentFragment\[/code\]. This is because IE8 does not give \[code\].sourceIndex\[/code\] on those nodes. (It doesn't give \[code\].contains\[/code\] either but I've fixed that problem already)How do I efficiently write the \[code\]+=4\[/code\] and \[code\]+=2\[/code\] bit which correspond to DOCUMENT_POSITION_FOLLOWING and DOCUMENT_POSITION_PRECEDING.For extra reference those two are defined by tree-order which DOM4 defines as \[quote\] An object A is preceding an object B if A and B are in the same tree and A comes before B in tree order. An object A is following an object B if A and B are in the same tree and A comes after B in tree order. The tree order is preorder, depth-first traversal.\[/quote\]Most modern browsers implement this (including IE9). So you only need something that works in IE8 (I don't care about IE6/7, but if it works awesome!)
 
Top