Relative position in DOM elements in jQuery

Given the two jquery objects, is there some way that I will tell you which one is “further ahead” in the document tree than the other? In other words, with a document

 <p id="p1" ></p>
 <div id="div1">
    <p id="p2"></p>
 </div>
 <p id="p3"></p>

Is there any function that behaves this way?

$("#p1").isBefore($("#p2")); // == true
$("#p3").isBefore($("#p2")); // == false
$("#p1").isBefore(#("#p3")); // == true

Please note that I am concerned about the position in the HTML tree of the document, not the physical position on the screen.

+3
source share
2 answers

You can make a function that does this, for example:

(function($) {
  $.fn.isBefore = function(elem) {
    if(typeof(elem) == "string") elem = $(elem);
    return this.add(elem).index(elem) > 0;
  }
})(jQuery)

You can try here , the first line is so that it can also take the selector line directly, for example:

$("#p1").isBefore("#p2");

.add() ( ) ( jQuery ), , .

, , , true, - "" , , , , $("p").isBefore("#p2") true, <p> "" #p2.

+12

:

alert($('#p1,#p2')[0]===$('#p1')[0]);
alert($('#p3,#p2')[0]===$('#p3')[0]);
alert($('#p1,#p3')[0]===$('#p1')[0]);

... , .

:

(function($) {
  $.fn.isBefore = function(elem) {
    return ($([elem.selector,this.selector].join(','))[0]===this[0]);
  }
})(jQuery);
+2

Source: https://habr.com/ru/post/1767988/


All Articles