Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare order of two HTML elements

I have a function which accepts two parameters, each of type HTML element. It is supposed to return which element appears first in the document order. Is there any simple way to determine this?

Template -

 <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
}
like image 368
user Avatar asked Mar 22 '26 21:03

user


1 Answers

You can try with Node.compareDocumentPosition()

The Node.compareDocumentPosition() method compares the position of the given node against another node in any document.

The syntax is 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>
like image 157
Shubh Avatar answered Mar 24 '26 11:03

Shubh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!