I am facing an issue with appending a row into a table's body. I wrote the whole logic part, but I cannot get the desired solution to work. I have a tablewith some rows and columns; I also have one button for calculating the total price of the items.
On button click I want to create a row showing the total price of the items.
Here is my code:
function calcTotal() {
let sum = 0;
let price = document.querySelectorAll(".price");
for (let i = 0; i < price.length; i++) {
sum = sum + parseInt(price[i].innerHTML);
}
console.log(sum);
const tbody = document.getElementsByName("tbody");
const row = document.createElement("tr");
row.innerHTML = '<td>' + Grand - Total + '</td><td data-ns-test="grandTotal">' + sum + '</td>';
tbody[0].appendChild(row);
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Grocery List</h1>
<table>
<thead>
<tr>
<th>Sr. No.</th>
<th>Title</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Item-1</td>
<td data-ns-test="price" class="price">100</td>
</tr>
<tr>
<td>2</td>
<td>Item-2</td>
<td data-ns-test="price" class="price">200</td>
</tr>
<tr>
<td>3</td>
<td>Item-3</td>
<td data-ns-test="price" class="price">2</td>
</tr>
<tr>
<td>4</td>
<td>Item-4</td>
<td data-ns-test="price" class="price">1</td>
</tr>
</tbody>
</table>
<button onClick='calcTotal()'>Total</button>
<script src="app.js"></script>
</body>
</html>