2

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.

2
  • 1
    cell1.id='id here' Commented Nov 24, 2015 at 8:04
  • or row.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>' Commented Nov 24, 2015 at 8:05

1 Answer 1

7

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 tds 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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.