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" >

<div id="div1"> <p id="p2">

</div> <p id="p3">

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.


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)

<a href="http://jsfiddle.net/nick_craver/8wBbv/2/" rel="nofollow">You can try it out here</a>, the first line is so it can also take a selector string directly, for example:


What this does is <a href="http://api.jquery.com/add/" rel="nofollow">.add()</a> 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 <em>any</em> 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

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


  • Convert 2D string array into 2D int array (Multidimensional Arrays)
  • Powershell - Create a folder from a file name, then place that file in the folder
  • How to programatically change the startColor attribute of gradient - Android
  • odbc driver does not support the requested properties
  • Generic Swift function to test for object type
  • ASP.NET Mvc Api: Set cookie then 302/303 Redirect loses the cookie
  • WCF List serialization/deserialization error
  • Looping through a list of images in JSP and calling a servlet to display each one in a table, but th
  • When is quoting necessary in prepared statements of pdo in PHP?
  • MySql query to find rooms available given dates 'From' and 'to'
  • openOptionsMenu() across android versions
  • Reuse jQuery object from an iframe?
  • How would I make a polygon based on the relative positions of markers in google maps?
  • Starting activity from phonegap plugin-webIntent
  • how to submit mapreduce job with yarn api in java
  • import cv2 doesn't give error on command-Prompt but error on IDLE on Windows 10, Python 3.6.4
  • how does heapq.merge in python work
  • How can I progmatically click a link in a Winform Web Browser control?
  • CameraPreviewImageSource empty preview frame
  • ClearCase can I use clearexport_ccase/clearimport to copy VOB data to a VOB on a different machine
  • How can I access the Google account user_id?
  • Querying Elasticsearch Address Based Index
  • dmtracedump doesn't work, HELP!
  • Content-Type alternative in MQTT
  • How to turn off notice reporting in xampp?
  • how to run ejabberd with Erlang on Heroku?
  • Functions by reference or by variable, which to use when?
  • Why my AngularJS async test in Jasmine 1.3.x is not working?
  • Capture SIGFPE from SIMD instruction
  • Call Microservice from another Microservice within Docker
  • Using Service Component Runtime
  • How to use FirstOrDefault inside Include
  • How do I use TagLib-Sharp to write custom (PRIV) ID3 frames?
  • Firebase: How to read from external DB?
  • WPF custom control and direct content support
  • CAS 4 - Not able to retrieve the LDAP groups after successful authentication
  • Create/delete users from text file using Bash script
  • Time Complexity of Fibonacci Algorithm [duplicate]
  • How to check if object is null in Java?