比较两个HTML元素的顺序

use*_*ser 0 html javascript

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

范本-

 <body>
     <div id="div1">
          <div id="div2">
          </div>
     </div>
     <div id="div3">
        <div id="div4">
        </div>
     </div>
</body>
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

Shu*_*ubh 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');
}
Run Code Online (Sandbox Code Playgroud)
<div id="a"></div>

<div id="b"></div>
Run Code Online (Sandbox Code Playgroud)