wxs
wxs

Reputation: 5837

Relative position in DOM of elements in jQuery

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.

Upvotes: 3

Views: 956

Answers (2)

Dr.Molle
Dr.Molle

Reputation: 117334

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);

Upvotes: 2

Nick Craver
Nick Craver

Reputation: 630409

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.

Upvotes: 12

Related Questions