joymis Posted March 16, 2017 Share Posted March 16, 2017 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. Link to comment Share on other sites More sharing options...
astralaaron Posted March 16, 2017 Share Posted March 16, 2017 I would look into jquery's closest() function which will search up the dom until it finds what it is looking for. Once you found the tr I think you could use jquery's index() index function closest() https://api.jquery.com/closest/ index() https://api.jquery.com/index/ 1 Link to comment Share on other sites More sharing options...
ibrahimjan Posted March 16, 2017 Share Posted March 16, 2017 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 Link to comment Share on other sites More sharing options...
joymis Posted March 16, 2017 Author Share Posted March 16, 2017 it's work. Thank you for your help. Link to comment Share on other sites More sharing options...
Ingolme Posted March 16, 2017 Share Posted March 16, 2017 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 Link to comment Share on other sites More sharing options...
joymis Posted March 20, 2017 Author Share Posted March 20, 2017 On 2017/3/16 at 7:26 PM, Ingolme said: 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 ok, thank you for your help Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now