MacMan MacMan - 1 year ago 151
jQuery Question

Jquery - get nearest TR ID by Class?

I'm using a jquery to move table rows and when I release the row I'd like to get the ID for the nearest TR which has the class


When the row I'm moving is released I get it's ID using:

var row_id = $(row).prop('id');
console.log (row_id)

which results in

How do I get the ID of the TR nearest to
with the class

This is the table layout.

<tr id="present_sprints" class="group_heading nodrag">
<td colspan="4">LIST1</td>
<tr id="sprint_145664" style="cursor: move;">
<td>First round - in sprint</td>
<tr id="sprint_145975" class="toggler_row" style="cursor: move;">
<td>Third round</td>
<tr id="sprint_145966" class="toggler_row" style="cursor: move;">
<td>Release prep</td>
</tr><tr id="sprint_145665" class="toggler_row" style="cursor: move;">
<td>Second round</td>

<tr id="future_sprints" class="group_heading nodrag">
<td colspan="4">Future Sprints</td>
<tr id="sprint_145964" class="toggler_row" style="cursor: move;">
<td>Fifth run</td>
<tr id="sprint_145965" class="toggler_row" style="cursor: move;">
<td>Fourth round</td>
<td><input type="text" value="2012-10-13" <="" td="">

For the example above I'd be looking to get ID = 'present_sprints'

If the the ID of the moved row was sprint_145965, I'd expect the ID for the nearest TR with class group_heading to be future_sprints

How do I do this ?

I've tried:


But that didn't work..


Answer Source

You are looking for .prevAll() instead of .closest(). You can use .eq() to get only the first one. And you should use .attr() instead of .prop().

var heading = $('#sprint_145975').prevAll('.group_heading').eq(0);
console.log( heading.attr('id') );

heading = $('#sprint_145964').prevAll('.group_heading').eq(0);
console.log( heading.attr('id') );
<script src=""></script>

  <tr id="present_sprints" class="group_heading"></tr>
  <tr id="sprint_145975"></tr>
  <tr id="future_sprints" class="group_heading"></tr>
  <tr id="sprint_145964"></tr>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download