Search code examples
javascriptjqueryhtml-table

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>

Solution

  • 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>