JavaScript 中克隆元素并更改其 ID
JavaScript 要克隆一个元素并更改其 id:
-
使用
cloneNode()
方法克隆元素。 - 在元素上设置不同的 id 属性。
-
例如,
clone.id = 'another-id'
。
以下是本文示例的 HTML。
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box"> <p>Child 1</p> <p>Child 2</p> </div> <script src="index.js"></script> </body> </html>
这是相关的 JavaScript 代码。
const box = document.getElementById('box');
// ✅ Clone node and its descendants
const clone = box.cloneNode(true);
// ✅ Change clone's id
clone.id = 'cloned-box';
// 👇️ Add clone to body
document.body.appendChild(clone);
我们使用 getElementById()
方法来选择我们想要克隆的元素。
我们在元素上调用了 cloneNode
方法。
cloneNode()
方法返回调用它的节点的副本。
该方法采用的唯一参数是节点的后代是否也应该被克隆。
如果设置为 false,则只会克隆节点,不包括子元素和文本节点。
我们将 clone 的 id 属性设置为 cloned-box 的值。
我们也可以使用 setAttribute
方法来获得相同的结果。
const box = document.getElementById('box');
// ✅ Clone node and its descendants
const clone = box.cloneNode(true);
// ✅ Change clone's id
clone.setAttribute('id', 'cloned-box');
// 👇️ Add clone to body
document.body.appendChild(clone);
setAttribute
方法有两个参数:
- name - 要设置其值的属性的名称。
- value - 分配给属性的值。
如果该属性已存在于元素上,则更新该值,否则添加具有指定名称和值的新属性。
最后一步是使用 appendChild
方法将元素添加到 DOM。
在示例中,我们在主体上调用了该方法,但是它可以在任何节点上调用。
appendChild 方法将一个节点添加到调用它的元素的子元素列表的末尾。
应该注意的是,
cloneNode
方法不会复制使用addEventListener()
方法添加的事件侦听器和分配给元素属性的事件,例如box.onclick = function()
。
如果我使用示例中的代码加载页面,我可以看到 div 元素已被克隆并且其 id 已成功更改。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。