hakkidilek
hakkidilek

Reputation: 151

Insert to Table Thead JS

I have a table field like the one below. What I want to do exactly here is to add external thead and values ​​to the table with javascript. The Thead tag will never change.

<table id="firm_table">

    <tbody>
    <tr>
        <td>1</td>
        <td>31</td>
        <td>100</td>
        <td>120</td>
        <td>0</td>
    </tr>
    <tr>
        <td>2</td>
        <td>32</td>
        <td>89</td>
        <td>102</td>
        <td>0</td>
    </tr>
    </tbody>
</table>

How Can add constant thead as below

<thead>
    <tr>
        <th>id</th>
        <th>product_id</th>
        <th>Purchase price</th>
        <th>Sale price</th>
        <th> Stock</th>
    </tr>
</thead>

Upvotes: 0

Views: 520

Answers (2)

Wais Kamal
Wais Kamal

Reputation: 6180

Use node.insertBefore():

var yourTable = document.querySelector("table"); // select your table
var thead = document.createElement("thead");
var row = document.createElement("tr");
var theadCells = ["id", "product_id", "Purchase price", "Sale price", "Stock"];
for(var i = 0; i < theadCells; i++) {
  var cell = document.createElement("th");
  cell.innerHTML = theadCells[i];
  row.appendChild(cell);
}
thead.appendChild(row);
yourTable.insertBefore(thead, yourTable.children[0]);

A dirty way but much shorter: put your markup in a string and add it to your table:

var thead = "<thead><tr><th>id</th><th>product_id</th><th>Purchase price</th><th>Sale price</th><th>Stock</th></tr></thead>"
yourTable.innerHTML = thead + yourTable.innerHTML;

Upvotes: 2

Maksim Koronchik
Maksim Koronchik

Reputation: 107

With jQuery:

const thead = `
<thead>
    <tr>
        <th>id</th>
        <th>product_id</th>
        <th>Purchase price</th>
        <th>Sale price</th>
        <th> Stock</th>
    </tr>
</thead>`;
$('#firm_table').prepend(thead);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="firm_table">

    <tbody>
    <tr>
        <td>1</td>
        <td>31</td>
        <td>100</td>
        <td>120</td>
        <td>0</td>
    </tr>
    <tr>
        <td>1</td>
        <td>32</td>
        <td>89</td>
        <td>102</td>
        <td>0</td>
    </tr>
    </tbody>
</table>

Upvotes: 2

Related Questions