Reputation: 1133
I have a simple table, where I have set IDs for headers and IDs for rows. Given an ID for both, I need to find a corresponding cell at the intersection of those two.
Example:
<table id="tablica">
<thead>
<th id="bla">Bla</th>
<th id="bli">Bli</th>
<th id="blu">Blu</th>
</thead>
<tbody>
<tr id="jedan">
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr id="dva">
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr id="tri">
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
</tbody>
</table>
So if I have id="bli" and id="dva", that means I want to do something with cell having value 5 in this example.
edit: There are a lot of correct answers, I upvoted all of them, but unfortunately I can only choose one as correct.
Upvotes: 14
Views: 34837
Reputation: 3065
If you have got the id of the row you can select the column having data 5 into it.
$("#dva").find("td:contains(5)").css({"background-color":"red"});
Also refer this fiddle as working example.
EDIT Without knowing the id of the row you only have id to table, then you can also find the cell :
$("#tablica tr").find("td:contains(5)").css({"background-color":"red", "padding":"5px"});
Upvotes: 3
Reputation: 3226
Here is my solution:
var column = $('#bli').index();
var cell = $('#dva').find('td').eq(column);
And working example on jsfiddle: http://jsfiddle.net/t8nWf/2/
added all in a function:
function getCell(column, row) {
var column = $('#' + column).index();
var row = $('#' + row)
return row.find('td').eq(column);
}
Working example: http://jsfiddle.net/t8nWf/5/
Upvotes: 13
Reputation: 53929
This will get you the TD element you want as a jQuery object:
var thIndex = $( '#tablica #bli' ).index (); // get index of TH in thead
var $td = $( $( '#dva td' ).get ( thIndex ) ); // get the TD in the target TR on the same index as is in the thead
Upvotes: 1
Reputation: 4588
$('#dva > td').eq($('#bli').index()); // returns the td element
should work. Working example: http://jsbin.com/acevon/edit#javascript,html,live
Upvotes: 2