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

I tried to add the same element to HTML document several times but it doesn't work, I don't know the reason. The code looks like this:

<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 result

  Very
  Secret
**Child**

      

instead

  Very
  Secret
**Child**
**Child**
**Child**

      

+3
javascript


source to share


4 answers


DOM manipulation techniques, such as insertBefore

and appendChild

move elements if they are already in the DOM tree. This is why you ended up adding only one node.

If you want to create three different nodes, you have several options.

1). Cloning node . Using cloneNode

, you can add the cloned node instead of the 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 add HTML string instead of NodeElement. The most convenient way 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/

+4


source to share


You must create the item three times.

This way you just create one item and set 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/

+1


source to share


When you add a node to another node, you are not cloning it.

Refer to to actually clone node. Node.cloneNode

+1


source to share


Try to clone 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);

      

+1


source to share







All Articles
Loading...
X
Show
Funny
Dev
Pics