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,
<开发者_如何学Pythondiv 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?
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';
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
精彩评论