How to return the row and column index of a table cell by clicking
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>
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)
})
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>