tags:

views:

84

answers:

1

I have a table full of tabular data. I need to find the index of a column(cell) in the table.

For example:

<table>
<tr>
<td>Column1</td>
<td>Column2</td>
<td>Column3</td>
</tr>
<tr>
<td>foo</td>
<td>bar</td>
<td>foobar</td>
</tr>
</table>

function TestIndexOf(someTD)
{
$(someTD) // what's my column index?  
}
+4  A: 

$('td').prevAll().length will give you the 0-based index of a cell

Alternatively using index() (can pass a DOM element or a jQuery object in. If jQuery object, only the first object in the wrapped set is used)

var cell = $('td'); // select on cell
cell.parent().index(cell);

If I recall correctly, index() will be easier to use in jQuery 1.4 and will allow you to simply call index() on the element wrapped in a jQuery object to get the index, like so

$('td').index() // NOTE: This will not work in versions of jQuery less than 1.4

So for your function

function TestIndexOf(someTD) {
    return $(someTD).prevAll().length; 
}
Russ Cam
Perfect. I actually searched for index in the jquery docs, but failed to find it. Maybe I'm blind. Thanks again.
Darthg8r
I highly recommend downloading the documentation here - http://docs.jquery.com/Downloading_jQuery#Documentation under **API Reference**. Using the Search in the HTML files is far easier to navigate than the site.
Russ Cam