Ibrahim Azhar Armar
Ibrahim Azhar Armar

Reputation: 25755

get position (index) of td element identified by class name


i have this code

<tr id="3" class="gradeA odd focus row_selected">
    <td class="center">Kids Footwear 2</td>
    <td class="sorting_1 center focus">200</td>
    <td class="center">50</td>
    <td class="center">200</td>
    <td class="center">30-34</td>
    <td class="center">234-343</td>
    <td class="center">200</td>
    <td class="center">25</td>
    <td class="center">1.23</td>
</tr>

i want to fetch the index value of <td> element which contains the class focus

so if within the <td> element the focus class is set on

first `<td>` then return 0
second `<td>` then return 1
third `<td>` then return 2 

and so on.how do i go with this in jQuery?

thank you.

Upvotes: 1

Views: 3257

Answers (1)

James Allardice
James Allardice

Reputation: 166021

You can use the index method. If you have more than one tr element containing a td with the focus class then you will probably want to make the selector specific to the tr you care about:

var index = $("td.focus").index();

From the jQuery docs:

If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.

Update (see comments)

You can use children or find to get the td elements from the tr, and then use the above code:

var index = tr.find("td.focus").index();

Upvotes: 2

Related Questions