Skip to content
Advertisement

Jquery retrieve an attribute value for the selected rowIndex

I have an event when a table cell is clicked that is fired properly. Then, I am trying to get the row index of that selected cell, but I always get “undefined”.

I see the correct rowIndex value from $this object, but how to get it? Seems a basic question but I tried different syntax and javascript and jquery methods and I am not able to get the value.

enter image description here

html:

enter image description here

Advertisement

Answer

rowIndex is a property of the <tr> so you’ll want to navigate up the DOM hierarchy to retrieve it.

jQuery($ => {
  $("td").on("click", function() {
    const selectedToolTableIndex = this.closest("tr").rowIndex
    
    console.log("row index", selectedToolTableIndex)
  })
})
td { cursor: pointer; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1">
  <tr>
    <td>Row #1</td>
  </tr>
  <tr>
    <td>Row #2</td>
  </tr>
  <tr>
    <td>Row #3</td>
  </tr>
</table>

If you need Internet Explorer support, use this instead as IE does not support Element.closest()

var selectedToolTableIndex = $(this).closest("tr").prop("rowIndex")

This will use jQuery’s .closest() to navigate to the parent <tr>, then retrieve the rowIndex property via .prop().

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement