Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 225
Eran Medan Avatar asked Mar 09 '12 19:03

Eran Medan


3 Answers

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.
like image 112
David Thomas Avatar answered Sep 22 '22 00:09

David Thomas


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

like image 39
Jasper Avatar answered Sep 23 '22 00:09

Jasper


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

$(function(){
    $('#search').click(function(){
        $('td').each(function(index){
            if ($(this).text() == $('#lookup').val()){
                console.log(index)
            }
        });    
    });   
});​
like image 39
Justice Erolin Avatar answered Sep 25 '22 00:09

Justice Erolin