Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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**
like image 721
Huibin Zhang Avatar asked Dec 25 '22 02:12

Huibin Zhang


2 Answers

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/

like image 175
dfsq Avatar answered May 18 '23 21:05

dfsq


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/

like image 30
Michael Avatar answered May 18 '23 20:05

Michael