Reputation: 1110
I tried to add same element to the HTML document multiple times, but it doesn't work, I don't know the reason. The code is following:
<html>
<body>
<div>Very</div>
<div>Secret</div>
<script>
var elem = document.createElement('div')
elem.innerHTML = '**Child**'
document.body.insertBefore(elem,document.body.lastChild);
document.body.insertBefore(elem,document.body.lastChild);
document.body.insertBefore(elem,document.body.lastChild);
</script>
</body>
</html>
why the result is
Very
Secret
**Child**
instead of
Very
Secret
**Child**
**Child**
**Child**
Upvotes: 4
Views: 1982
Reputation: 193291
DOM manipulation methods like insertBefore
and appendChild
move elements if they are already in DOM tree. That's why you end up with only one node appended to the end.
If you want to create three different nodes, then you have a couple of options.
1). Cloning node. Using cloneNode
you can append cloned node instead of original:
var elem = document.createElement('div')
elem.innerHTML = '**Child**';
document.body.insertBefore(elem.cloneNode(true), document.body.lastChild);
2). String as template. You can append HTML string instead of NodeElement. The most convenient method for this manipulation is insertAdjacentHTML
:
var elem = '<div>**Child**</div>';
document.body.lastElementChild.insertAdjacentHTML('afterend', elem);
document.body.lastElementChild.insertAdjacentHTML('afterend', elem);
document.body.lastElementChild.insertAdjacentHTML('afterend', elem);
Upvotes: 7
Reputation: 771
Try to clone the node.
var elem = document.createElement('div')
elem.innerHTML = '**Child**'
document.body.insertBefore(elem,document.body.lastChild);
document.body.insertBefore(elem.cloneNode(true),document.body.lastChild);
document.body.insertBefore(elem.cloneNode(true),document.body.lastChild);
Upvotes: 1
Reputation: 175017
When you append a node to a different node, you aren't cloning it.
See the Node.cloneNode
method to actually clone a node.
Upvotes: 1
Reputation: 3326
You should create the element for three times.
In the way you did you are just creating one element and setting it three times:
function myFun() {
var elem = document.createElement('div')
elem.innerHTML = '**Child**'
return elem;
}
document.body.insertBefore(myFun(), document.body.lastChild);
document.body.insertBefore(myFun(), document.body.lastChild);
document.body.insertBefore(myFun(), document.body.lastChild);
Upvotes: 1