是否可以在 JavaScript 中克隆 html 元素对象?

2022-08-30 05:01:35

我在表格中有一个html元素(如选择框输入字段)。现在我想复制对象并从副本中生成一个新对象,并使用JavaScript或jQuery。我认为这应该以某种方式工作,但我现在有点无能为力。

像这样的东西(伪代码):

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

newDdl = oldDdl;

oldDdl.attr('id', newId);

oldDdl.html();

答案 1

使用原生 JavaScript:

newelement = element.cloneNode(bool)

其中,布尔值指示是否克隆子节点。

这是关于MDN的完整文档


答案 2

使用你的代码,你可以使用 cloneNode() 方法在普通的 JavaScript 中执行类似操作:

// Create a clone of element with id ddl_1:
let clone = document.querySelector('#ddl_1').cloneNode( true );

// Change the id attribute of the newly created element:
clone.setAttribute( 'id', newId );

// Append the newly created element on element p 
document.querySelector('p').appendChild( clone );

或者使用jQuery clone()方法(不是最有效的):

$('#ddl_1').clone().attr('id', newId).appendTo('p'); // append to where you want