joymis

How can I get tr index

6 posts in this topic

Hello,

I have some html code like this

<table>
  <thead>....</thead>
  <tbody id="content">
    <tr>
      <td>
      	<img ......>
        <img onclick="test()" src="1.jpg">
      </td>
    </tr>
    <tr>
      <td><img onclick="test()" src="3.jpg"></td>
    </tr>
    <tr>
      <td>
        <img ......>
        <img ......>
        <img onclick="test()" src="2.jpg">
      </td>
    </tr>
  </tbody>
</table>

when I onclick 3.jpg, I want get tr index is 1, and I onclick 1.jpg, I want get tr index is 0

how can I use jQuery or javascript get the tr index and no use like parentNode api?

because I not sure parentNode of img must be td, maybe it's div, span, or a table.

Thanks.

Share this post


Link to post
Share on other sites

Like astralaaron said using closest class and the index class in jquery you can get the index of the tr, have a look at the fiddle. https://jsfiddle.net/8hL46ftj/

hope this helps ;)

$('img').click(function(){

alert($(this).closest('tr').index())

})

 

2 people like this

Share this post


Link to post
Share on other sites

You can also do this without jQuery using the rowIndex property of the table row element: https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableRowElement/rowIndex

If you have a reference to the image, you can get to the table row using the parentNode property

1 person likes this

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now