比较两个HTML元素的顺序

时间:2019-06-20 07:20:29

标签: javascript html

我有一个函数,该函数接受两个参数,每个参数都是HTML元素类型。应该返回哪个元素首先出现在文档顺序中。有什么简单的方法可以确定这一点吗?

模板-

 <body>
     <div id="div1">
          <div id="div2">
          </div>
     </div>
     <div id="div3">
        <div id="div4">
        </div>
     </div>
</body>

JS-

const elem1 = document.getElementById('div2');
const elem2 = document.getElementById('div4');
const firstAppearingElement = checkOrder(elem1, elem2); // it should return elem1
function checkOrder(element1, element2) {
    // check which one appears first in dom tree
}

1 个答案:

答案 0 :(得分:8)

您可以尝试使用Node.compareDocumentPosition()

  

Node.compareDocumentPosition()方法比较对象的位置   给定的节点与任何文档中的另一个节点。

语法为object.compareDocumentPosition (nodeToCompare);

let first = document.getElementById('a');
let second=document.getElementById('b');

// Because the result returned by compareDocumentPosition() is a bitmask, the bitwise AND operator has to be used for meaningful results.See link above for more

if (first.compareDocumentPosition(second) & Node.DOCUMENT_POSITION_FOLLOWING) {
  console.log('element with id a is before element with id b'); // 
} else {
  console.log('element with id a is after element with id b');
}
<div id="a"></div>

<div id="b"></div>