10

Please see the fiddle. When I click the cell, I can get the value and the column name. I wonder how can I get the row and column index instead? Following is the js code,

<script type="text/javascript">

    $(document).ready(function(){
        $('#example tbody').on( 'click', 'td', function () {
            alert('Data:'+$(this).html().trim());
            alert('Row:'+$(this).parent().find('td').html().trim());
            alert('Column:'+$('#example thead tr th').eq($(this).index()).html().trim());
        });
    });

</script>
1

5 Answers 5

20

Another Native JS way to do this is using TableData properties that can be found when using table elements. For example, cellIndex will return the column index of a td element and rowIndex will return the index of a tr element. These two properties will simplify our code by a ton, shown on the following code.

const cells = document.querySelectorAll('td');
cells.forEach(cell => {
  cell.addEventListener('click', () =>
    console.log("Row index: " + cell.closest('tr').rowIndex + " | Column index: " + cell.cellIndex));
});
<table>
  <tr>
    <td>0:0</td>
    <td>0:1</td>
    <td>0:2</td>
    <td>0:3</td>
  </tr>
  <tr>
    <td>1:0</td>
    <td>1:1</td>
    <td>1:2</td>
    <td>1:3</td>
  </tr>
  <tr>
    <td>2:0</td>
    <td>2:1</td>
    <td>2:2</td>
    <td>2:3</td>
  </tr>
</table>

5
  • 1
    this is by far the cleanest vanilla approach
    – gilad905
    Commented Apr 12, 2020 at 0:27
  • Very nice. Wondering how the term 'cellIndex' came to be, rather than 'colIndex'. A table with ten rows will have ten cells with the identical cellIndex value.. Commented Mar 12, 2021 at 23:42
  • 3
    This answer is wrong if there are cells with rowSpan > 1. The term cellIndex is correct since it is the index of the cell in its parent row's cell array. But cellIndex != colIndex with rowSpans. Consider <table> <tr> <td rowSpan="2"> A </td> <td> B </td> </tr> <tr> <td> C </td> </tr> </table> . Cell "C" has a cellIndex of 0 since it is the first child of its <tr>, but is actually in column 1 since Cell A occupies the row=1, col=0 table location
    – waldol1
    Commented Apr 28, 2022 at 19:31
  • @waldol1 thanks for the feedback, but for the case shown in the fiddle, it is correct. Although, you make an interesting point for the case where “rowSpan” is used.
    – Alain Cruz
    Commented Apr 28, 2022 at 19:34
  • I'll add that I believe this applies to all of the other answers as well, though perhaps jquery is hiding the rowSpan complications under the hood.
    – waldol1
    Commented Apr 28, 2022 at 19:36
6

No need for jQuery, you can achieve it with native JS:

const table = document.querySelector('table');
const rows = document.querySelectorAll('tr');
const rowsArray = Array.from(rows);

table.addEventListener('click', (event) => {
  const rowIndex = rowsArray.findIndex(row => row.contains(event.target));
  const columns = Array.from(rowsArray[rowIndex].querySelectorAll('td'));
  const columnIndex = columns.findIndex(column => column == event.target);
  console.log(rowIndex, columnIndex)
})
5

The best probably would be to use closest here:

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

<script type="text/javascript">

    $(document).ready(function(){
        $('#example tbody').on( 'click', 'td', function () {
            alert('Row ' + $(this).closest("tr").index());
            alert('Column ' + $(this).closest("td").index());
        });
    });

</script>
3

index() can do the job. Just find the correct collection and current elements, to do elementCollcetions.index(currentElement)

    $(document).ready(function(){
        $('#example tbody').on('click', 'td', function () {
               
	    alert('ColumnIndex:'+ $(this).parent().find('td').index(this));
	    alert('RowIndex:'+ $(this).parent().parent().find('tr').index($(this).parent()));
            
        });
    });
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="example"><tbody>
<tr><td>11</td><td>12</td></tr>

<tr><td>21</td><td>22</td></tr>
</tbody>
</table>

0

use this

$(document).ready(function(){
    $('#example tbody').on( 'click', 'td', function () {   

        var column_num = parseInt( $(this).index() );
        alert('column index:'+column_num );

        var row_num = parseInt( $(this).parent().index() );  
        alert('rowindex:'+row_num );
    });
});

Not the answer you're looking for? Browse other questions tagged or ask your own question.