Search code examples
javascripthtmlrowrow-number

How to display row number in HTML table in specific column?


I have a table in HTML that has 5 columns. The first column is the "row number", where I want to show which row it is--starting from 1.

Here's a picture

I have tried using this CSS:

body {
    /* Set the Serial counter to 0 */
    counter-reset: Serial; 
}

table {
    border-collapse: separate;
}

tr td:first-child:before {
    /* Increment the Serial counter */
    counter-increment: Serial;

    /* Display the counter */
    content: "Serial is: " counter(Serial); 
}

Solution

  • Here is the working code for this:

    <html>
        <head>
            <script type="text/javascript">
            function displayResult()
            {
                var index = document.getElementById("myTable").rows.length;
                var new_row = '<td>'+index+'</td><td>cell 1</td><td>cell 2</td>';
                document.getElementById("myTable").insertRow(-1).innerHTML = new_row;
            }
            </script>
        </head>
    
        <body>       
            <table id="myTable" border="1">
                <tr>
                `   <td>0</td>
                    <td>cell 1</td>
                    <td>cell 2</td>
                </tr>
    
            </table>
            <br />
            <button type="button" onclick="displayResult()">Insert new row</button>            
        </body>
    </html>