Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return the row and column index of a table cell by clicking

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>
like image 738
WCMC Avatar asked Aug 13 '17 04:08

WCMC


3 Answers

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>
like image 142
Alain Cruz Avatar answered Nov 09 '22 21:11

Alain Cruz


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)
})
like image 20
Avraam Mavridis Avatar answered Nov 09 '22 21:11

Avraam Mavridis


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>
like image 42
Axalix Avatar answered Nov 09 '22 22:11

Axalix