admin管理员组

文章数量:1327939

Given two jquery objects, Is there some way I tell 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 some function that behaves thus?

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

Note that I care about position in the HTML tree of the document, not physical position on the screen.

Given two jquery objects, Is there some way I tell 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 some function that behaves thus?

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

Note that I care about position in the HTML tree of the document, not physical position on the screen.

Share Improve this question asked Oct 5, 2010 at 1:45 wxswxs 5,8575 gold badges39 silver badges52 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 12

You can make a function that does this, like this:

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

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

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

What this does is .add() the additional element (or selector) (which jQuery keeps in document order) and then checks if it's the second of the two.

If the selector this is run against has more than one element, this returns true if any of those elements are "before" the passed in element or selector, so given your markup for example $("p").isBefore("#p2") would be true, since at least one <p> occurs "before" #p2.

You can try it that way:

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

...fetch both objects and look which is the first.

function for better usability:

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

本文标签: javascriptRelative position in DOM of elements in jQueryStack Overflow