i’m trying to write some dynamic code and i can’t be sure the element i’m after is sibling or child of a sibling.
i just have a class and must search for the first element that has this class after my element.
example:
<something class='EitherMe'/>
<table>
<thead class = 'EitherMe'></thead>
<tbody>
<tr class = 'selectAfterThis'><td></td></tr>
.
.
.
</tbody>
<tfoot class ='EitherMe'>
<tr></tr>
<tr class='OrMe'></tr>
</tfoot>
</table>
<something class='OrMe'/>
i’ll get ‘EitherMe’ or ‘OrMe’ depending on the user’s need. and i need to select exactly the element with that class that comes after ‘selectAfterThis’
nextAll() doesn’t work. since it only gets the siblings.
is there any way to do this?
update: i put the thead in the above example.since most suggestion were going through the parent. and i don’t really know if there is no element with class higher up.
i could limit my plugin by limiting the class’s exact location but i want to avoid that if possible.
update2: simply put, i need the element with the specified class, that comes below ‘selectAfterThis’, whether its just below him, or far below him, or its parent-child relationship with ‘selectAfterThis’ doesn’t matter
update 3: here’s a mini plugin i wrote from wirey’s answer. hope it helps anyone else who has a problem like me: http://jsfiddle.net/jTLt2/4/ . all credits go to wirey. i just did a few modifications to make it go deeper than just parent sibling and child of parents siblings.
please let me know if you test it. i want to know if it works 100%
here’s the code :
(function($){
$.fn.nextInView = function(selector)
{
var ret = this.nextAll(selector);
for(var i = 0;this.parents().eq(i).find('body').length < 1 ;i++){
ret = ret.add(this.parents().eq(i).nextAll(selector));
ret = ret.add(this.parents().eq(i).nextAll().find(selector));
}
return ret.first();
}
})(jQuery)
You need to separately add them into a collection.. then get the first out of the collection to find the closest one
http://jsfiddle.net/fRq4z/