Issue
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>
Solution
In my example, the forEach method is used. And the button is also created using the createElement() method:
let button = document.createElement('button');
Next, a th tag will be created to place the button there:
let td = document.createElement('td');
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!
let tr = document.querySelectorAll("table tbody tr");
Array.from(tr).forEach(function(trArray) {
let button = document.createElement("button");
let td = document.createElement("td");
button.innerText = "buy";
button.className = "btn_buy";
td.append(button);
trArray.append(td);
});
<table>
<thead>
<tr>
<th>Product Name</th>
<th>Description</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>Soap</td>
<td>good for babies</td>
<td>75</td>
</tr>
<tr>
<td>Milk</td>
<td>manufactured</td>
<td>100</td>
</tr>
<tr>
<td>Rice</td>
<td>red rice 1kg pack</td>
<td>130</td>
</tr>
</tbody>
</table>
Answered By - s.kuznetsov
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.