Is it possible to clone html element objects in JavaScript / JQuery?

Richard picture Richard · May 28, 2009 · Viewed 112.2k times · Source

I am looking for some tips on how to solve my problem.

I have a html element (like select box input field) in a table. Now I want to copy the object and generate a new one out of the copy, and that with JavaScript or jQuery. I think this should work somehow but I'm a little bit clueless at the moment.

Something like this (pseudo code):

oldDdl = $("#ddl_1").get(); 

newDdl = oldDdl;

oldDdl.attr('id', newId);

oldDdl.html();

Answer

annakata picture annakata · May 28, 2009

With native JavaScript:

newelement = element.cloneNode(bool)

where the Boolean indicates whether to clone child nodes or not.

Here is the complete documentation on MDN.