Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery find previous table row that has a cell with a specific class

Tags:

jquery

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?

like image 872
theShingles Avatar asked May 05 '10 23:05

theShingles


2 Answers

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.

like image 71
Nick Craver Avatar answered Nov 22 '22 11:11

Nick Craver


How about:

var label = 
  $('.selected').parent().prevAll('tr').children('td.this-is-a-label')[0];
like image 42
Chris Lercher Avatar answered Nov 22 '22 09:11

Chris Lercher