JQuery / Javascript - How to find table heading index by heading text

What is a good way to find a column index displaying text?

eg.

<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 this? (It doesn't have to be jQuery, but it would be nice)

+4
source share
3 answers

The following 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 an OP question, in the comments below:

but how to limit it to the first line?

To limit it to the first line, simply use the :first selector:

 $('tr:first td') 

Donation:

 $('tr:first td').filter( function(){ return $(this).text() == 'Name'; }).index(); 

JS Fiddle demo .

Literature:

+16
source
 //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() function, if you return true for the index, then it will be saved in the selection, and if you return false , then this 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 is used by ID ).

Note that .index() , when used as described above, will return the index of the current selection based on its sibling elements: http://api.jquery.com/index

+2
source

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

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

Source: https://habr.com/ru/post/1400646/


All Articles