views:

40

answers:

2

Hi,

I would like to clone a tag using Javascript (without using any external frameworks like jQueries, so please limit the answer to plain Javascript)

Here is my requirement. Say I have a random div like the following in the document,

<div id='anEmptyDiv' style="display:none">
    <div>
      Lorem Ipsum
    </div>
</div>

And I should be able to do something like this,

var customDiv = document.getElementyById('anEmptyDiv');
var copyDiv = clone(customDiv);
copyDiv.id = 'a_valid_id';
copyDiv.style.display = 'block';

There is a reason behind I this question. I have a structured DIV tag which I want to use many times when some event occurs. I want the structure alone and I dont intend to create the DOM tree everytime. Is this possible in Javascript?

A: 

via http://www.w3schools.com/dom/dom_nodes_clone.asp

xmlDoc=loadXMLDoc("books.xml");

oldNode=xmlDoc.getElementsByTagName('book')[0];
newNode=oldNode.cloneNode(true);
xmlDoc.documentElement.appendChild(newNode);

//Output all titles
y=xmlDoc.getElementsByTagName("title");
for (i=0;i<y.length;i++)
{
document.write(y[i].childNodes[0].nodeValue);
document.write("<br />");
} 

The key function here is cloneNode

marcgg
Perfect! this is what i was looking for!! Thanks!
Bragboy
why the downvote? the OP said it was what he was looking for...
marcgg
+2  A: 

You could try the cloneNode function:

var customDiv = document.getElementById('anEmptyDiv');
var copyDiv = customDiv.cloneNode(true);
copyDiv.id = 'a_valid_id';
copyDiv.style.display = 'block';
Darin Dimitrov