Eran Medan
Eran Medan

Reputation: 45725

JQuery / Javascript - How to find the index of a table header by the header text

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)

Upvotes: 8

Views: 16708

Answers (3)

David Thomas
David Thomas

Reputation: 253318

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:

Upvotes: 22

Justice Erolin
Justice Erolin

Reputation: 2879

http://jsfiddle.net/justiceerolin/FdhcV/

$(function(){
    $('#search').click(function(){
        $('td').each(function(index){
            if ($(this).text() == $('#lookup').val()){
                console.log(index)
            }
        });    
    });   
});​

Upvotes: 1

Jasper
Jasper

Reputation: 76003

//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

Upvotes: 2

Related Questions