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

Picture of Amitpal Singh
Amitpal Singh
September 8, 2020

Auto number table rows with CSS and JS


1. CSS Method

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;
}

2. JS method – 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>

3. JS method – 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>

Share this post:

How to Attribute?

Lorem ipsum is typically a corrupted version of De finibus bonorum et malorum, a 1st-century BC text by the Roman statesman and philosopher Cicero.
for Example: Website, Social Media, Blogs, ebooks , newsletter, etc.
Lorem ipsum is typically a corrupted version of De finibus bonorum et malorum, a 1st-century BC text by the Roman statesman and philosopher Cicero.
Copied!

Got a Question? Check out our FAQ Section.

Your action, our appreciation

It encourage us to give you more valuable content on website.