Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
32
rated 0 times [  36] [ 4]  / answers: 1 / hits: 15880  / 12 Years ago, fri, march 9, 2012, 12:00:00

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)


More From » jquery

 Answers
18

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:




[#86948] Thursday, March 8, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
chelseyn

Total Points: 36
Total Questions: 85
Total Answers: 89

Location: Laos
Member since Fri, Sep 11, 2020
4 Years ago
;