开发者

Insert HTML element two (or more) times using JavaScript

开发者 https://www.devze.com 2023-03-10 19:09 出处:网络
How do I insert a HTML element twice using JavaScript? This code isn\'t working: var div = document.createElement(\'div\');

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/


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


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消