Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto-number table rows?

I have the following HTML table:

<table border="1">   <tr>     <td>blue</td>   </tr>   <tr>     <td>red</td>   </tr>   <tr>     <td>black</td>   </tr> </table> 

I would like each row in this table have a number automatically assigned to each item.

How could he do?

like image 290
Marcio Avatar asked Jun 09 '13 17:06

Marcio


People also ask

Can you automatically number rows in Excel?

Luckily, Excel provides a way to number your rows automatically without using the drag button: the fill series function. The Excel fill series function is used to generate sequential values within a specified range of cells. Unlike the fill handle function, this function gives you much more control.


2 Answers

The following CSS enumerates table rows (demo):

table {    counter-reset: rowNumber;  }    table tr::before {    display: table-cell;    counter-increment: rowNumber;    content: counter(rowNumber) ".";    padding-right: 0.3em;    text-align: right;  }
<table cellpadding="0">    <tr><td>blue</td></tr>    <tr><td>red</td></tr>    <tr><td>yellow</td></tr>    <tr><td>green</td></tr>    <tr><td>purple</td></tr>    <tr><td>orange</td></tr>    <tr><td>maroon</td></tr>    <tr><td>mauve</td></tr>    <tr><td>lavender</td></tr>    <tr><td>pink</td></tr>    <tr><td>brown</td></tr>  </table>

If the CSS cannot be used, try the following JavaScript code (demo):

var table = document.getElementsByTagName('table')[0],    rows = table.getElementsByTagName('tr'),    text = 'textContent' in document ? 'textContent' : 'innerText';    for (var i = 0, len = rows.length; i < len; i++) {    rows[i].children[0][text] = i + ': ' + rows[i].children[0][text];  }
<table border="1">    <tr>      <td>blue</td>    </tr>    <tr>      <td>red</td>    </tr>    <tr>      <td>black</td>    </tr>  </table>
like image 110
David Thomas Avatar answered Sep 20 '22 16:09

David Thomas


And if you would use headers as well the following is the thing you need: http://jsfiddle.net/davidThomas/7RyGX/

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

note the: ":not(:first-child)" in there.

like image 37
user3691833 Avatar answered Sep 19 '22 16:09

user3691833