Suppose I have a table like so:
<table>
<tr><td class="this-is-a-label">Label Cell</td></tr>
<tr><td>Detail 1</td></tr>
<tr><td class="selected">Detail 2</td></tr>
</table>
I want to be able to grab the previous "Label Cell" from the "Selected" cell.
My jQuery script should be something like:
$('.selected').each(function() {
var label = $(this).parent().prev('tr td.this-is-a-label');
//... do what I need with the label ...
});
But it's not working.
Does anyone have any suggestions?
You can do this:
$('.selected').each(function() {
var label = $(this).closest('tr').prevAll('tr:has(td.this-is-a-label):first')
.children('td.this-is-a-label');
//... do what I need with the label ...
});
This isn't ideal though, it's a rather expensive DOM traversal, if you can guarantee it's always 2 rows behind, you can do this:
$(this).closest('tr').prev().prev().children('td.this-is-a-label')
...which is much faster, it just depends what assumptions and guarantees you can make about your markup, if there are any certainties, you can definitely make it faster.
How about:
var label =
$('.selected').parent().prevAll('tr').children('td.this-is-a-label')[0];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With