从节点确定文档顺序

Mic*_*ael 7 html javascript dom

如果我在HTML文档中有两个节点,如何使用DOM方法在Javascript中以HTML文档顺序排出哪个节点?

例如,

function funstuff(a, b) {
    //a and b can be any node in the DOM (text, element, etc)
    if(b comes before a in document order) {
        var t = b; b = a; a = t;
    }
    // process the nodes between a and b. I can handle this part 
    // when I know that a comes before b.
}
Run Code Online (Sandbox Code Playgroud)

Cre*_*esh 5

救援人员:

// Compare Position - MIT Licensed, John Resig
function comparePosition(a, b){
  return a.compareDocumentPosition ?
    a.compareDocumentPosition(b) :
    a.contains ?
      (a != b && a.contains(b) && 16) +
        (a != b && b.contains(a) && 8) +
        (a.sourceIndex >= 0 && b.sourceIndex >= 0 ?
          (a.sourceIndex < b.sourceIndex && 4) +
            (a.sourceIndex > b.sourceIndex && 2) :
          1) +
      0 :
      0;
}
Run Code Online (Sandbox Code Playgroud)