Reputation: 4625
I am trying to find that is the order of the <td>
in a <tr>
. I have a table structure like this
<table>
<tbody>
<tr>
<th> Name </th>
<th> Edit </th>
<th> Delete </th>
<tr>
<tr>
<td> Tom </td>
<td> <i class="icon icon_edit"></i> </td>
<td> <i class="icon icon_remove"></i> </td>
<tr>
<tbody>
</table>
I have to find table header <th> Edit </th>
using the <i class="icon icon_edit">
. I was trying to find it using the parents() but still didnt got any method to find the position of the parent <td>
in the row.
My logic is like this
parentTD = $('.icon_edit').parents('td')
positionOfparentTD = 2 //Which i dont know how to
correspondingHeader = $("table th:eq(2)")
How can I implement this in jQuery?
Upvotes: 0
Views: 617
Reputation: 6268
I would rather use a class on the header, because if you change the order of the columns some day, your Javascript will probably forgotten to be updated and therefore will not work anymore.
Here is what I would do:
<table>
<thead>
<tr>
<th>Name</th>
<th class="edit-header">Edit</th>
<th>Delete</th>
<tr>
</thead>
<tbody>
<tr>
<td>Tom</td>
<td class="edit"><i class="icon icon_edit"></i></td>
<td><i class="icon icon_remove"></i></td>
<tr>
<tbody>
</table>
And then would do this with jQuery:
var $editHeader = $('.edit').parents('thead').find('.edit-header');
I added the edit
class as well on the edit cell, because the icon class name might change as well.
Upvotes: 0
Reputation: 318302
jQuery has an index()
method, it's zero based but so is eq()
var parentTD = $('.icon_edit').closest('td')
var positionOfparentTD = parentTD.index(); // 1
var correspondingHeader = $("table th:eq("+positionOfparentTD+")")
Upvotes: 3
Reputation: 67207
Try using .index() and i would suggest you to use .closest() instead of .parents(),
parentTD = $('.icon_edit').closest('td');
positionOfparentTD = parentTD.index();
correspondingHeader = $("table th:eq("+ positionOfparentTD +")")
Upvotes: 1
Reputation: 22619
var tdIndex=$('.icon_edit').parent('td').index();
$("table th:eq('"+ tdIndex+"')");
Upvotes: 1