'How to insert row in table through Javascript function
I am trying to insert another row into a table with footer.
Here is my code:
function submit(){
/* Some code here with declarations & value assignings*/
let tble = document.getElementById("tabl");
let newEl = document.createElement("tr");
newEl.innerHTML="<td>"+nowSr+"</td> <td>"+taskForm+"</td> <td>"+tagForm+"</td> <td>Rs. "+amountForm+"</td>";
tble.appendChild(newEl, tble.lastElementChild.previousSibling.lastElementChild);
}
My function gives me below result:

As you can see (IN INSPECT ELEMENTS WINDOW) the new row is inserted after the footer. How to add it properly
- after the last row in the table?
Solution 1:[1]
Don't insert the element directly to the <table> element, but select the <tbody> instead.
You can do that like that:
function submit(){
let tble = document.getElementById("tabl");
let newEl = document.createElement("tr");
newEl.innerHTML="<td>"+nowSr+"</td> <td>"+taskForm+"</td> <td>"+tagForm+"</td> <td>Rs. "+amountForm+"</td>";
tble.querySelector('tbody').appendChild(newEl, tble.lastElementChild.previousSibling.lastElementChild);
}
But you shouldn't use innerHTML to create the row (it could create an XSS vulnerability), use innerText or textContent instead. But that means that you have to create the <td>s differently:
function submit(){
let tble = document.getElementById("tabl");
let newEl = document.createElement("tr");
appendTD(newEl, nowSr);
appendTD(newEl, taskForm);
appendTD(newEl, tagForm);
appendTD(newEl, "Rs. "+amountForm);
tble.querySelector('tbody').appendChild(newEl, tble.lastElementChild.previousSibling.lastElementChild);
}
function appendTD(tr, text){
const td = document.createElement('td')
td.innerText = text
tr.appendChild(td)
}
Solution 2:[2]
Try puhsing to the tbody intead of the table directly
function addTableRow(){
const tbody = document.querySelector('#myTable tbody')
const newRow = document.createElement('tr')
newRow.innerHTML = `<td>Foo</td><td>Bar</td>`
tbody.appendChild(newRow)
}
<table id="myTable">
<thead>
<tr>
<th>Helo</th>
<th>World</th>
</tr>
</thead>
<tbody>
<tr>
<td>Foo</td>
<td>bar</td>
</tr>
</tbody>
</table>
<button onclick="addTableRow()">Add row</button>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | RenaudC5 |
