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.
讨论(0)
-
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:
- Set a temporary attribute to each element with the same value
- Use a jquery selector to locate the first element with that attribute value
讨论(0)
-
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')
}
});
讨论(0)
- 热议问题