Adding row numbers to an HTML table using the browser's JavaScript console

Published on 2024-10-12 • Modified on 2024-10-12

This snippet shows how to add row numbers to an HTML table using the browser's JavaScript console. Open your browser's JavaScript console, copy/paste the snippet below and see the magic happen. Note that you can also select the table by class; in this case use getElementsByClassName() instead of getElementsByTagName(), and in the lines below replace table. with table[0].


// Select the table class
const table = document.getElementById('myTable');

// Add the new colum name in the header
const head = table.getElementsByTagName('thead')[0].rows;
const newColumn = head[0].insertCell(0);
newColumn.innerHTML = "Rank";

// Finally, add the rank to each row
const rows = table.getElementsByTagName('tbody')[0].rows;
for (let i = 0; i < rows.length; i++) {
    const newCell = rows[i].insertCell(0);
    newCell.innerHTML = i + 1;
}
HTML demo of the snippet
Name Score
COil 10
Jmsche 8
Wouterj 5

 More on Stackoverflow   Read the doc  Random snippet

  Work with me!


Call to action

Did you like this post? You can help me back in several ways: (use the "reply" link on the right to comment or to contact me )

Thank you for reading! And see you soon on Strangebuzz! 😉

COil