jQuery: select last parent of child element
How would I get the top most level of tr
by selecting the ones that have spans in the following HTML:
<table>
<tr><!-- THIS ONE -->
<td>
<table>
<tr>
<td><span></span></td>
</tr>
</table>
</t开发者_JS百科d>
<td><span></span></td>
</tr>
<tr><!-- AND THIS ONE -->
<td><span></span></td>
<td><span></span></td>
</tr>
</table>
So something like:
$('table span').parent('tr:last')
Though, unfortunately, that only returns a single tr...
use the :has selector eg. table#topmost > tr:has(span)
Your HTML is invalid to begin with. You never actually open a <tr>
tag, you only try to close them (</tr>
).
Probably:
$('table span').parentsUntil('tr');
But that won't work because the way you have this formatted the TRs are siblings, not parents
So in that case...change your HTML to -
<table>
<tr>
<td>
<table>
<tr>
<td><span></span></td>
</tr>
</table>
</td>
<td><span></span></td>
</tr>
<tr>
<td><span></span></td>
<td><span></span></td>
</tr>
</table>
and the javascript above will work.
It seems to me that the top most level will always be in the topmost table, so you only have to check those rows
$('#topmost-table>tr:has(span)').stuff();
<table id="topmost-table">
<tr>
<td>
<table>
<tr>
<td><span></span></td>
</tr>
</table>
</td>
<td><span></span></td>
</tr>
<tr>
<td><span></span></td>
<td><span></span></td>
</tr>
</table>
$(document).ready(function() {
$('table span').each(function(){
//do something with each tr you find
$(this).parents('tr:last');
});
});
精彩评论