What is a good way to find the index of column by it's display text?
e.g.
<table>
<tr>
<td>ID</td>
<td>Name</td>
<td>Age</td>
</tr>
<tr>
...
</tr>
</table>
I would like to have something like
var nameIndex = getColIndex('Name'); // nameIndex = 1
Is there a quick / good way to do it? (Doesn't have to be jQuery, but would be nice)
The following both seem to work, in Chromium 17/Ubuntu 11.04:
$('tr td').filter(
function(){
return $(this).text() == 'Name';
}).index();
JS Fiddle demo.
Or:
$('td:contains("Name")').index();
JS Fiddle demo.
Edited in response to OP's question, in comments, below:
but how do I limit it to the first row?
To limit it to the first row, simply use the :first
selector:
$('tr:first td')
Giving:
$('tr:first td').filter(
function(){
return $(this).text() == 'Name';
}).index();
JS Fiddle demo.
References:
:contains()
.filter()
.:first
.//select the first TR element, then select its children (the TDs),
//then filter them down to only the one that contains a certain string
var theIndex = $('tr').first().children().filter(function () {
return ($(this).text() == 'ID');
}).index();
When passing .filter()
a function, if you return true
for an index, then it will be kept in the selection, and if you return false
then that index will be removed from the selection: http://api.jquery.com/filter
This will limit the search to the first row and give the index of the column with the specified search text (this code used ID
).
Note that .index()
, when used like above, will return the index of the current selection based on its sibling elements: http://api.jquery.com/index
http://jsfiddle.net/justiceerolin/FdhcV/
$(function(){
$('#search').click(function(){
$('td').each(function(index){
if ($(this).text() == $('#lookup').val()){
console.log(index)
}
});
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With