24

I'm trying to find the index of a row in a table. I'm trying to use the following code, but I seem to get an index of -1.

$(document).ready(function()
{
    $("tr").click(function (){
        var index = $("table").index($(this));
        $("span").text("That was row index #" + index);
    });
});

With html that looks like this;

<table>
<tbody>
    <tr><td>click</td></tr>
    <tr><td>click</td></tr>
    <tr><td>click</td></tr>
    <tr><td>click</td></tr>
</tbody>

Thanks

1
  • var index = $(this).index(); Commented May 4, 2017 at 15:15

5 Answers 5

41

Have you tried:

$("tr").index(this)

The documentation shows just passing this and that the preceding selection should be where the node is found. If you need to find it in a specific table (and there are multiple), you may need to provide some context:

// haven't tested this
$("tr", $(this).closest("table")).index(this) 
Sign up to request clarification or add additional context in comments.

3 Comments

From a child inside the row, $(this).closest("tr").index() does the trick. The second option in this answer doesn't work.
turns out this isnt necessary to be passed in the index function as it gave me -1 every time, using without this parameter works ok
Joshua's solution worked fine for me. I need to click a button from a TD.
11

Try:

var index = $("table tr").index(this);

The documentation for index() says:

Searches every matched element for the object and returns the index of the element, if found, starting with zero. If a jQuery object is passed, only the first element is checked.

You need to call the index() on a collection of <tr> elements, not the parent <table>.

3 Comments

Makes perfect sense. Getting -1 on everything though.
@stevek I edited the answer to remove the $() around this, since I'm not sure if jQuery would return the same object instance on calls to $ with the same node instance.
you dont need to pass this as the parameter just remove it and use .index() it will work correctly @Winnemucca
3

Based on Robs answer to find index in specific table, this worked for me.

var index = $('tr', $(this).closest("table")).index(this);

Comments

3

I've just found an interesting trick, which basically consists on counting the previous siblings:

var tr = $(some_selector);
var rowIndex = tr.prevAll().length;

This way you will get 0 if this is the first tr, 3 if this is the 4th tr, etc.

Just for the sake of it, another option using index(), which saves you from having to know how to select the containing table:

var rowIndex = tr.parent().children().index(tr);

Comments

1

Get the td object and its parent index is tr index

$(this).parent().index()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.