Let us suppose I have this markup
First
Hi
Hello
Second
Keeping in mind Rocket's answer I prefer to use .index()
approach like following:
$.fn.isAfter = function(sel){
return $(this).index() > $(sel).index();
};
$.fn.isBefore= function(sel){
return $(this).index() < $(sel).index();
};
It seems more clear for reading/understanding and works perfectly in rows selection.
The accepted answer only works if the elements are at the same level. One approach to solve it if you want to locate which element is first regardless of the level is:
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')
}
});