Reputation: 8053
By first I mean that opening tag of one element is earlier in HTML than the opening tag of the second.
2 elements can be totally random, can be siblings, or one can be an ascendant or descendant of the other. So the solution should be a function taking 2 random DOM elements and checking which is first in the DOM hierarchy.
Upvotes: 3
Views: 278
Reputation: 318182
You can use Node.compareDocumentPosition()
to do that
var node1 = document.getElementById('test1');
var node2 = document.getElementById('test2');
if ( node1.compareDocumentPosition(node2) & Node.DOCUMENT_POSITION_FOLLOWING ) {
// node 1 comes before node2
} else {
// node 2 comes before node1
}
<div id="test1"></div>
<div id="test2"></div>
it returns bitmask values that tells you the first nodes position in regards to the second node
1 = DOCUMENT_POSITION_DISCONNECTED
2 = DOCUMENT_POSITION_PRECEDING
4 = DOCUMENT_POSITION_FOLLOWING
8 = DOCUMENT_POSITION_CONTAINS
16 = DOCUMENT_POSITION_CONTAINED_BY
32 = DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC
One could do something similar in jQuery using index()
, but it won't be nearly as efficient
$.fn.comesBefore = function(elem) {
var all = $('*');
return all.index(this) < all.index($(elem));
}
var node1 = $('#test1');
var node2 = $('#test2');
var result = node1.comesBefore(node2); // false, node1 comes after node2
document.body.innerHTML = result;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div id="test2"></div>
</div>
<div id="test1"></div>
Upvotes: 7