Inserting A Clone After The Original
I'm trying to place a clone element after the original element. I did some research and found out how to create a clone and how to place the clone after the original, but I can't s
Solution 1:
Close. :-) You call it on the parent node (and no need to go look it up a second time):
functiononClickAdd() {
var tableRow = document.getElementById("tableRow");
var tableRowClone = tableRow.cloneNode(true);
tableRow.parentNode.insertBefore(tableRowClone, tableRow.nextSibling);
// ^^^^^^^^^^^^^^^^^^^--- changes here
}
Of course, the above creates an invalid DOM structure, because you end up with two rows with the same id
value ("tableRow"
), and id
values must be unique in the document. So:
functiononClickAdd() {
var tableRow = document.getElementById("tableRow");
var tableRowClone = tableRow.cloneNode(true);
// Clear the `id` from the clone
tableRowClone.id = ""; // To clear it, or include something to give it its own
tableRow.parentNode.insertBefore(tableRowClone, tableRow.nextSibling);
// ^^^^^^^^^^^^^^^^^^^--- changes here
}
Solution 2:
You have to use insertBefore
on the parent element:
tableRow.parentNode.insertBefore(tableRowClone, tableRow.nextSibling);
And do not forget to change the id
. IDs must be unique.
And, in the inline event, Javascript:
is obsolete. It doesn't cause any errors, because it's being interpreted as a label.
Solution 3:
functiononClickAdd() {
var tableRow = document.getElementById("tableRow");
var tableRowClone = tableRow.cloneNode(true);
tableRow.parentNode.insertBefore(tableRowClone, tableRow.nextSibling);
}
And the demo.
Post a Comment for "Inserting A Clone After The Original"