Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert HTML element two (or more) times using JavaScript

How do I insert a HTML element twice using JavaScript?

This code isn't working:

var div = document.createElement('div');
div.innerText = 'Hello!';
document.body.appendChild(div);
document.body.appendChild(div);

Test: http://jsfiddle.net/9z82D/

like image 886
Tyilo Avatar asked Jun 05 '11 18:06

Tyilo


3 Answers

Ok I found that you just have to use cloneNode:

var div = document.createElement('div');
div.innerText = 'Hello!';
document.body.appendChild(div);
var div2 = div.cloneNode(true);
document.body.appendChild(div2);
like image 156
Tyilo Avatar answered Nov 17 '22 05:11

Tyilo


To elaborate on your answer, appendChild is not making a copy of your element 'div' and appending it to the end of the body, it's moving the actual node.

So if you have two elements, div and div2, and you do:

document.body.appendChild(div);
document.body.appendChild(div2);
document.body.appendChild(div);

div gets inserted to the end of the body, then div2, then div gets moved from the top to the bottom. (see http://jsfiddle.net/9z82D/3/ )

This is helpful, because any changes you make to div after you append it after still reflected in the object div. If this wasn't the case, you'd have to do an additional getElementsByTagName to recapture the element before making any other changes.

For example, try div.innerText='goodbye'; after you've appended the node-- the text will update without having to append again.

like image 34
Jeff Avatar answered Nov 17 '22 05:11

Jeff


Instead of cloning and creating multiple variables, you could just loop it:

for(i=0;i<2;i++)
 {
  var div = document.createElement('div');
  div.innerText = 'Hello!';
  document.body.appendChild(div);  
}
like image 2
jk. Avatar answered Nov 17 '22 05:11

jk.