简体   繁体   中英

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>

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>

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM