Using Javascript, I am trying to add a new table row into the the middle of a table, where the new table row is a copy of one of the pre-existing rows.
There are a lot of questions similar to this on stackoverflow, but none seemed to help me solve this problem.
function AddRow()
{
var mainTable = document.getElementById('mainTable');
mainTable.insertBefore(
mainTable.rows[0].cloneNode(true),
mainTable.rows.childNodes[2]);
}
I know the problem exists in the last variable passed to insertBefore(), as if I leave this blank the code performs correctly and inserts the cloned first row at the end of the table (if no 2nd parameter is present, it acts like appendRow().
I get the error "Cannot read property 2 of undefined", which I guess means it's not recognising mainTable.rows.childNodes as a valid object to be indexing.
I have also tried the following method, and got the more elusive error "NotFoundError: DOM Exception 8" when testing it
function AddRow()
{
var mainTable = document.getElementById('mainTable');
mainTable.insertBefore(
mainTable.rows[0].cloneNode(true),
mainTable.rows[2]);
}
EDIT: Note that mainTable.appendChild(mainTable.rows[0].cloneNode(true)) works fine! Problem is I don't want to add it the the end of the table.
insertBeforeassumes a direct child for the reference value.