Reputation: 273
I have this code for append a row to an existing table
$('#factorTable').append('<tr id="ft-' + id + '"><td id="ftn-' + id + '">' + name + '</td><td id="ftp-' + id + '">' + price + '</td><td id="ftNum-' + id + '">' + number + '</td><td id="ftSum-' + id + '">' + sum + '</td></tr>');
But I need to do it without using jQuery. How can I convert it to only native javascript I know that I can insert a row to a table using this code :
// Find a <table> element with id="myTable":
var table = document.getElementById("myTable");
// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(0);
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
// Add some text to the new cells:
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
However, as you see in my jQuery code, I need to add id
to <td>
and <tr>
tags.
Upvotes: 2
Views: 132
Reputation: 1074295
If you don't need to support IE8 or IE9, you can use insertAdjacentHTML
:
document.getElementById('factorTable').insertAdjacentHTML(
'beforeend',
'<tr id="ft-' + id + '"><td id="ftn-' + id + '">' + name + '</td><td id="ftp-' + id + '">' + price + '</td><td id="ftNum-' + id + '">' + number + '</td><td id="ftSum-' + id + '">' + sum + '</td></tr>'
);
But caniuse says that IE8 and IE9
(Throw) an "Invalid target element for this operation." error when called on a table, tbody, thead, or tr element.
As you're inserting a tr
with td
s in it, I assume you're calling this on a tbody
.
If you need IE9 (or earlier) support, we need to fall back on createElement
:
var tr = document.createElement('tr').
tr.id = 'ft-' + id;
tr.innerHTML = '<td id="ftn-' + id + '">' + name + '</td><td id="ftp-' + id + '">' + price + '</td><td id="ftNum-' + id + '">' + number + '</td><td id="ftSum-' + id + '">' + sum + '</td>';
document.getElementById('factorTable').appendChild(tr);
Upvotes: 7