Reputation: 534
I have table row object in my scope. And I can get it as a link is clicked on that row.
var tableRow = $(object).closest('tr');
What I need is to iterate this table columns of row by table header columns.
For example :
th1 th2 th3
tr1 td td td
tr2 td td td*
Lets say, I have tr2 in my scope, and I need to reach at cell under th3. When I iterate its cells, how can I know cell is under th3?
I want to that without using column index, but instead using column name.
Upvotes: 2
Views: 4287
Reputation: 33618
Iterate through each td of the row context and get the corresponding th of that column using .eq() and .index(). Something like below should work.
In this example I am searching for the column which has a th with text "two"
var $table = tableRow.closest('table');
var query = "two";
var result = tableRow.find('td').filter(function(){
return $table.find('th').eq($(this).index()).html() === query;
});
console.log(result.html());
$('tr').on('click', function() {
find($(this));
});
function find(tableRow) {
var $table = tableRow.closest('table');
var query = "two";
var result = tableRow.find('td').filter(function() {
return $table.find('th').eq($(this).index()).html() === query;
});
alert(result.html());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<th>One</th>
<th>two</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
</tbody>
</table>
Upvotes: 1
Reputation: 11358
assuming the id of your table is myTable, you can do:
$("#myTable td")
this will give you all table cells, if you iterate through them you will sweep from cell 1 to N.
if you need only, say the 2nd cell in each row, you can use the following selector:
$("#myTable tr td:nth-child(2)")
this will return you the 2nd cell in each row
Upvotes: 1