How do I insert a HTML element twice using JavaScript?
This code isn't working:
var div = document.createElement('div');
div.innerText = 'Hello!';
document.body.appendChild(div);
document.body.appendChild(div);
Test: http://jsfiddle.net/9z82D/
Ok I found that you just have to use cloneNode:
var div = document.createElement('div');
div.innerText = 'Hello!';
document.body.appendChild(div);
var div2 = div.cloneNode(true);
document.body.appendChild(div2);
To elaborate on your answer, appendChild is not making a copy of your element 'div' and appending it to the end of the body, it's moving the actual node.
So if you have two elements, div and div2, and you do:
document.body.appendChild(div);
document.body.appendChild(div2);
document.body.appendChild(div);
div gets inserted to the end of the body, then div2, then div gets moved from the top to the bottom. (see http://jsfiddle.net/9z82D/3/ )
This is helpful, because any changes you make to div after you append it after still reflected in the object div. If this wasn't the case, you'd have to do an additional getElementsByTagName to recapture the element before making any other changes.
For example, try div.innerText='goodbye';
after you've appended the node-- the text will update without having to append again.
Instead of cloning and creating multiple variables, you could just loop it:
for(i=0;i<2;i++)
{
var div = document.createElement('div');
div.innerText = 'Hello!';
document.body.appendChild(div);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With