user
user

Reputation: 568

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
}

Upvotes: 2

Views: 942

Answers (1)

Shubham Dixit
Shubham Dixit

Reputation: 1

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>

Upvotes: 9

Related Questions