Huibin Zhang
Huibin Zhang

Reputation: 1110

Javascript insertBefore method cannot be called mulitple times adding same child node?

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

Answers (4)

dfsq
dfsq

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);

Demo: http://jsfiddle.net/xh3nqe85/

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);

Demo: http://jsfiddle.net/xh3nqe85/1/

Upvotes: 7

Alvin Magalona
Alvin Magalona

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

Madara&#39;s Ghost
Madara&#39;s Ghost

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

Michael
Michael

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);

http://jsfiddle.net/6zppunvv/

Upvotes: 1

Related Questions