JSFiddle - React, Tailwind, and code Playground

by Karl-Henry Martinsson

HTML

<table id="tbl">
  <tr class="header">
    <th>S. No.</th>
    <th>First Name</th>
    <th>Last Name</th>
    <th>City</th>
    <th>Country</th>
  </tr>
  <tr class="row">
    <td>1</td>
    <td>Bill</td>
    <td>Gates</td>
    <td>Washington</td>
    <td>U.S</td>
  </tr>
  <tr class="row">
    <td>2</td>
    <td>Elon</td>
    <td>Mask</td>
    <td>Pretoria</td>
    <td>South Africa</td>
  </tr>
</table>
<button id="btnAddAbove" class="btnAdd">Add row to top</button>
<button id="btnAddBelow" class="btnAdd">Add row to bottom</button>

JavaScript

// Bind to click event on buttons
$(".btnAdd").on("click", function(){
	// Get highest existing number and add 1
  let rowNum = parseInt(getHighestNumber()) + 1;
  // The next 4 lines should be populated with values from elsewhere
  let firstname = "myFirstName";
  let lastname = "myLastName";
  let city = "myCity";
  let country = "myCountry";
  // Build HTML to insert
	let html = `<tr class="row">
    <td>${rowNum}</td>
    <td>${firstname}</td>
    <td>${lastname}</td>
    <td>${city}</td>
    <td>${country}</td>
  </tr>`;
  // Get which button was clicked
  let btn = $(this).attr("id");
  if (btn=="btnAddAbove") {
    // Insert the HTML after the header row, i.e. first in the actual table
    $(".header").after(html);
  } else if (btn=="btnAddBelow") {
    // Append the new row at the end of the table
  	$("#tbl").append(html);
  }
});

function getHighestNumber() {
  let highest = 0;
  // Select the first column of each row
	let firstCol = $("#tbl tr td:first-child");
  firstCol.each( function(index) {
    // Get number in first column
  	let num = $(this).html();
    if (num > highest) {
      highest = num;
    }
  });
  return highest;
}