Dark

Light

Dark

Light

Scroll to top

How to index html table rows or how to Auto-number table rows?

CSS: Method 1

table {   
counter-reset: rowNumber;
}
table tr {
 counter-increment: rowNumber;
}
table tr td:first-child::before {   
content: counter(rowNumber);   
min-width: 1em;   
margin-right: 0.5em;
}

JS: Method 2 (append with a new td)

<script>   
var tables = document.getElementsByTagName(‘table’);   
var table = tables[tables.length -1];   
var rows = table.rows;   
for(var i = 0, td; i < rows.length; i++){           
td = document.createElement(‘td’);       
td.appendChild(document.createTextNode(i + 1));       
rows[i].insertBefore(td, rows[i].firstChild);   
}
</script>

JS: Method 3 (append with in first td)

<script>
var table = document.getElementsByTagName(‘table’)[0],   
rows = table.getElementsByTagName(‘tr’),    text = ‘textContent’ in document ? ‘textContent’ : ‘innerText’;
console.log(text);
for (var i = 0, len = rows.length; i < len; i++)
{   
rows[i].children[0][text] = i + ‘: ‘ + rows[i].children[0][text];
}
</script>

Author avatar
Amitpal Singh
https://amitpalsingh.com

Post a comment

Your email address will not be published. Required fields are marked *