Is it possible to clone html element objects in JavaScript? Ask Question

Is it possible to clone html element objects in JavaScript? Ask Question

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

ベストアンサー1

The modern approach is to use the cloneNode function:

let new_element = element.cloneNode(true);

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

Afterwards, you can add the cloned element to DOM somewhere. For example, you can use after() to insert the new element right after the original element:

element.after(new_element);

Compatibility:

Browser compatibility for Element.after

Browser compatibility for Node.cloneNode

おすすめ記事