<table>
<tbody>
<tr>
<td class="TargetRow">Not this one</td>
</tr>
</tbody>
<tbody> ... </tbody>
<tbody>
<tr>
<td class="TargetRow">This one</td>
</tr>
</tbody>
<tbody> ... </tbody>
<tbody>
<tr class="ContextRow"> ... </tr>
</tbody>
</table>
Given the above HTML I'm trying to find a way of getting the contents of the preceding tr of class TargetRow. I.e. for the first preceding tbody that contains a td.TargetRow return the td.TargetRow
I'm using jQuery, at present I can get hold of the tbody containing the ContextRow using:
jQ开发者_Python百科uery(contextRow).parents("tbody").first()
How can I now find the previous sibling of that tbody that contains tr.ContextRow?
If there was just a way for me to say from contextRow walk up the DOM tree until you find an element matching "td.TargetRow" then that would be ideal.
Many Thanks.
I'm a little confused by your description, but when you say "find the previous sibling of that tbody that contains tr.ContextRow" it sounds like you want to find the previous <tbody>
that contains an element with the class .contextRow
and get its .targetRow
.
If that's what you want, try this.
jQuery(contextRow).parents("tbody:first")
.prevAll('tbody:has(tr.ContextRow):first td.TargetRow');
If you meant to say td.TargetRow
then do 'tbody:has(td.TargetRow):first td.TargetRow'
.
jQuery('.ContextRow').closest("tbody").siblings('tbody td.TargetRow:last');
EDIT: last not first
see it work: http://jsfiddle.net/wU6h9/
$(".ContextRow").closest("tbody").prevAll().find(".TargetRow").eq(0).css({color: "red"});
This returns the single closest previous .TargetRow
http://jsfiddle.net/LfWg3/3/
Closest - .closest()
does exactly what you need.
Gets the first ancestor element that matches the selector, beginning at the current element and progressing up through the DOM tree.
Your query would be,
$('.ContextRow').closest('tbody').siblings('tbody td.TargetRow').last();
It will return one object( unlike parents, which returns multiple element until top), or zero if id didn't find one.
精彩评论