Answers for "html table auto counter for th"

0

html table auto counter for th

// Automatic Serial Number Row in HTML Table
<table class="css-serial">
  <thead>
    <tr>
      <th>#</th>
      <th>1st Column</th>
      <th>2nd Column</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <!--intentionally left blank-->
      <td></td>
      <td>Column 1</td>
      <td>Column 2</td>
    </tr>
    <tr>
      <!--intentionally left blank-->
      <td></td>
      <td>Column 1</td>
      <td>Column 2</td>
    </tr>
    <tr>
      <!--intentionally left blank-->
      <td></td>
      <td>Column 1</td>
      <td>Column 2</td>
    </tr>
  </tbody>
</table>

// The CSS
.css-serial {
  counter-reset: serial-number;  /* Set the serial number counter to 0 */
}

.css-serial td:first-child:before {
  counter-increment: serial-number;  /* Increment the serial number counter */
  content: counter(serial-number);  /* Display the counter */
}
//-----------------------------
// Or using JQ
function addRowCount(tableAttr) {
  $(tableAttr).each(function(){
    $('th:first-child, thead td:first-child', this).each(function(){
      var tag = $(this).prop('tagName');
      $(this).before('<'+tag+'>#</'+tag+'>');
    });
    $('td:first-child', this).each(function(i){
      $(this).before('<td>'+(i+1)+'</td>');
    });
  });
}

// Call the function with table attr on which you want automatic serial number
addRowCount('.js-serial');
//----------------------------------------------
// Or using Js

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

//=======================================
// src: https://mariusmateoc.com/blog/automatic-serial-number-row-in-html-table/
// src: https://stackoverflow.com/questions/17012421/auto-number-table-rows
Posted by: Guest on January-05-2021

Browse Popular Code Answers by Language