Michael Michael - 2 months ago 32
HTML Question

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?

Answer

The following CSS enumerates table rows (demo):

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

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;
}
<table border="1">
  <tr>
    <td>blue</td>
  </tr>
  <tr>
    <td>red</td>
  </tr>
  <tr>
    <td>black</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];
}

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>