简体   繁体   中英

How to add a BUTTON in to each HTML table rows using JAVASCRIPT

I have created a HTML table as below. I need to add a button after the Price of each product. How can I do this using JAVASCRIPT? (eg: Assume table has more than 20 rows. I need a button in each and every row)

 <table id="productTable" class="table table-bordered table-condensed table-striped"> <thead> <tr> <th>Product Name</th> <th>Description</th> <th>Price</th> </tr> </thead> <tbody> <tr> <th>Soap</th> <th>good for babies</th> <th>75</th> </tr> <tr> <th>Milk</th> <th>manufactured</th> <th>100</th> </tr> <tr> <th>Rice</th> <th>red rice 1kg pack</th> <th>130</th> </tr> </tbody> </table>

In my example, the forEach method is used. And the button is also created using the createElement() method:

var button = document.createElement('button');

Next, a th tag will be created to place the button there:

var th = document.createElement('th');

And a class is assigned to the button, with which you can refer to this button by class:

button.className = 'btn_buy';

With this code, a button is created for all table rows!

 window.onload = function() { var tr = document.querySelectorAll('#productTable tbody tr'); Array.from(tr).forEach(function(trArray, index) { var button = document.createElement('button'); var th = document.createElement('th'); button.innerText = 'buy'; button.className = 'btn_buy'; th.append(button); tr[index].append(th); }); }
 <table id="productTable" class="table table-bordered table-condensed table-striped"> <thead> <tr> <th>Product Name</th> <th>Description</th> <th>Price</th> </tr> </thead> <tbody> <tr> <th>Soap</th> <th>good for babies</th> <th>75</th> </tr> <tr> <th>Milk</th> <th>manufactured</th> <th>100</th> </tr> <tr> <th>Rice</th> <th>red rice 1kg pack</th> <th>130</th> </tr> </tbody> </table>

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