views:

41

answers:

2

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.

+5  A: 

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.

Nick Craver
Oh cool! What's the slow part here? Is add a particularly slow function?
wxs
@wxs - I had a brain lapse at first, this implementation above shouldn't have any speed issues :)
Nick Craver
Ah good. Yeah it didn't seem like it should be slow. Thanks a lot!
wxs
+2  A: 

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);
Dr.Molle
Hmm does this work? Does jQuery guarantee returning elements in the order they appear in the DOM?
wxs
No, it does'nt guarantee, sorry. I thought it will because it works with your example-markup, but in the documentation is written, that the order may differ. http://api.jquery.com/multiple-selector/
Dr.Molle
@DrMolle - The order may differ from the order *specified*, they will however be in *document* order...which is really what matters here, so your approach works, just not reusable easily:)
Nick Craver
If you say it, i will not disagree :). I never thought about the position till today. Added the function for easier use above
Dr.Molle