Check if element is before or after another element in jQuery

Rocket's solution works fine if sel is a real selector, if you pass a jquery object though, it won't work.

If you want a plugin that works with both selectors and jquery objects, just use my slightly modified version instead:

(function($) {
    $.fn.isAfter = function(sel){
        return this.prevAll().filter(sel).length !== 0;
    };

    $.fn.isBefore= function(sel){
        return this.nextAll().filter(sel).length !== 0;
    };
})(jQuery);

Kudos to Rocket for the original solution.


To see if an element is after another, you can use prev() or prevAll() to get the previous element(s), and see if it matches.

And to see if an element is before another, you can use next() or nextAll() to get the next element(s), and see if it matches.

$.fn.isAfter = function(sel){
  return this.prevAll(sel).length !== 0;
}
$.fn.isBefore= function(sel){
  return this.nextAll(sel).length !== 0;
}

DEMO: http://jsfiddle.net/bk4k7/


You can use the index() function:

$('p').each(function(){
   var index = $(this).index();
   if(index > $("#first").index() && index < $("#second").index()) {
     // do stuff
   }
});

Here is a fiddle

$('p').each(function() {
    previousH3 = $(this).prevAll('h3');
    nextH3 = $(this).nextAll('h3');

    if (previousH3.length > 0 && nextH3.length > 0) {
        $(this).css('color', 'red')
    }

});

I implemented a general isAfter function, which considers the depth and DOM tree and can correctly determine if a is after b even if they are in 2 different subtrees:

<div>
  <div>
    <p class="first">I come first</p>
  </div>
</div>

<div>
  <div>
    <p class="second">I come second</p>
  </div>
</div>

you can find it in my GitHub Repository. Would appreciate your feedback on the code