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**
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);
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);
http://jsfiddle.net/6zppunvv/
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