Jackbd Jackbd - 1 year ago 186
jQuery Question

Find table row index that contains text JQuery

I am trying to find table row index from a link which is on the table. The code I am trying, always returning value 3. I have two many rows on my page. My code is -

Table (example) -

<a herf="my link here" onclick="findindex(Rank1)">Rank1</a>

JQuery -

function findindex(RName) {
var val = $('table tbody tr td div a:contains(' + RName + ')').index();

Please someone help me how to find the table row index value.


Answer Source

When you call index() on that selector, you're in fact getting the index of the a element. The text selector is working fine, but after finding the element with the mached text, you need to find it's tr and get it's index:

$('table tbody tr td div a:contains("' + RName + '")').closest("tr").index();


Also, you have some syntax errors:


Should be:


Or even better:


And the function:

function findindex(element) {
    var val = $('table tbody tr td div a:contains("' + element.innerText + '")').closest("tr").index();
    alert(element.innerText + "=" + val);


Note that I have added quotes to your css selector:

'table tbody tr td div a:contains("' + element.innerText + '")'
                                  ^ this                    ^ and this

To produce this result 'table tbody tr td div a:contains("Rank1")'

Now, the best thing you can do with jQuery:

Remove the onclick event attribute from your anchor elements and add a class:

<a herf="my link here" class="rank-anchor">Rank1</a>

Then bind an event on document load to your table:

$("table").on("click", "a.rank-anchor", function() {
    var index = $(this).closest("tr").index();

In the event function, you can see that you don't need the full selector to the a element, you already have the element, so you can use this to find its tr. In this case you don't need to find the element by it's content as well, the event is being called fron it already.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download