If you’ve read previous entries in this series or are familiar with JS, you’ll know that it is pretty straightforward to remove an element from a page with JavaScript. Given this HTML:

如果您已阅读本系列的上一篇文章或对JS熟悉,那么您会知道, 使用JavaScript从页面中删除元素非常简单。 鉴于此HTML :

<h1>IF THE SUSPENSE DOESN’T KILL YOU
<span>SOMETHING ELSE WILL</span></h1>
<p id="open"><span>CLOSE ON GLASS VIALS</span> being lifted from a large medical refrigerator. Gloved hands slip them into a foam lined carry case. The vials are delicate. Filled with a cool blue liquid. The hands move quickly. Urgently.</p>
<p>Sleek, super hi—tech. The blinds are closed. Can’t tell if it’s day or night.</p>
<p>Typists type. Assistants assist.</p>
<p id="bees">Busy worker bees.</p>

In almost all modern browsers we can identify and remove the “bees” paragraph with:

在几乎所有现代浏览器中,我们可以通过以下方式识别和删除 “ bees”段落:

var bees = document.getElementById("bees");
bees.remove();

We could then move the “bees” paragraph to become the very first element in the page with the following:

然后,我们可以将“ bees”段落移动到页面中的第一个元素,其中包含以下内容:

document.body.insertBefore(bees, document.body.firstElementChild);

The DOM of the page would now be:

页面的DOM现在将是:

<p id="bees">Busy worker bees.</p>
<h1>IF THE SUSPENSE DOESN’T KILL YOU
<span>SOMETHING ELSE WILL</span></h1>
<p id="open"><span>CLOSE ON GLASS VIALS</span> being lifted from a large medical refrigerator. Gloved hands slip them into a foam lined carry case. The vials are delicate. Filled with a cool blue liquid. The hands move quickly. Urgently.</p>
<p>Sleek, super hi—tech. The blinds are closed. Can’t tell if it’s day or night.</p>
<p>Typists type. Assistants assist.</p>

This is the equivalent to “cut and paste” in JavaScript. But what if we identified “bees”, only to immediately place it as the first element? That should be the equivalent of “copy and paste” in JavaScript, right?

这等效于JavaScript中的“剪切和粘贴”。 但是,如果我们确定了“蜜蜂”,只有立即把它作为第一个元素? 那应该等同于JavaScript中的“复制和粘贴”,对吗?

var bees = document.getElementById("bees");
document.body.insertBefore(bees, document.body.firstElementChild);

The answer is “nope”: this gives us the same result as before, moving the element from the end of the document to the beginning. bees is a live reference to an element, and what we do to it is reflected directly in the DOM.

答案是“不”:这将为我们提供与以前相同的结果,将元素从文档末尾移至开头。 bees对元素实时引用 ,我们对它所做的工作直接反映在DOM中 。

You might think that we could create a new variable based on bees, and substitute that:

您可能会认为我们可以基于bees创建一个新变量 ,并将其替换为:

var bees = document.getElementById("bees");
var swarm = bees;
document.body.insertBefore(swarm, document.body.firstElementChild);

But that doesn’t work either: JavaScript considers bees exactly equivalent to swarm, and as referring to the same object, so the result is the same as before: the element is moved from point A to point B. What we need is a clone of the original object.

但这不起作用:JavaScript认为bees完全等于swarm ,并且引用了同一对象,因此结果与之前相同:该元素从A点移到B点。我们需要一个克隆原始对象。

var bees = document.getElementById("bees");
var swarm = bees.cloneNode(true);
document.body.insertBefore(swarm, document.body.firstElementChild);

Now the result is what we expect: a copy of bees at the start and end of the document.

现在的结果就是我们所期望的:在文档的开头和结尾处都有bees的副本。

cloneNode (cloneNode)

cloneNode makes exact duplicates of nodes, and has just one option: true or false. If true, cloneNode will include a copy of all the children from the original node. In the case of our example, true was necessary in order to gain a copy of the text of the paragraph, not just the markup.

cloneNode精确复制节点,只有一个选项: truefalse 。 如果为true ,则cloneNode将包括原始节点中所有节点的副本。 在我们的示例中,为获得段落文本的副本而不仅仅是标记是必要的,必须为true

With the true option cloneNode copies everything from the original node: applied styles, text, images, even JavaScript references (with the exception of any applied addEventListener). This exact duplication can lead to some issues, as we’ll see in a moment.

使用true选项, cloneNode复制原始节点中的所有内容 :应用的样式,文本,图像,甚至JavaScript引用(任何应用的addEventListener除外)。 稍后我们将看到,这种精确的重复会导致一些问题。

表里不一 (Duplicity)

One issue in our example is that we now have an exact duplicate of the original node, including its id:

我们的示例中的一个问题是,我们现在具有原始节点的精确副本, 包括id

<p id="bees">Busy worker bees.</p>
…
<p id="bees">Busy worker bees.</p>

This is bad: id attribute values should be unique references, and it’s very likely that our page will become deeply confused if we allow things to go on as they are. When creating node clones, you should be careful to check for and create new id values in the copies:

这很不好: id属性值应该是唯一的引用,并且如果我们允许事情继续进行,很有可能我们的页面会变得很混乱。 创建节点克隆时,应小心检查并在副本中创建新的id值:

var bees = document.getElementById("bees");
var swarm = bees.cloneNode(true);
swarm.id+= "copy";
document.body.insertBefore(swarm, document.body.firstElementChild);

In this case, we’ve concatenated the word copy to the original id value of the clone.

在这种情况下,我们将单词copy 连接到克隆的原始id值。

After we create them, clones go on to live their own lives: altering bees will not affect beescopy, and the reverse is also true: changes to clones do not affect their originals.

创建它们之后,克隆继续过自己的生活:改变bees不会影响beescopy ,反之亦然:克隆的更改不会影响其原始形式。

结论 (Conclusion)

cloneNode is an extremely useful method, allowing the web developer to quickly make multiple copies of almost anything and distribute them on the page. Then, those copies need to be manipulated… which is what this series will be looking at next.

cloneNode是一种非常有用的方法,它允许Web开发人员快速制作几乎所有内容的多个副本并将它们分发到页面上。 然后,需要对这些副本进行操作……这是本系列接下来的内容。

翻译自: https://thenewcode.com/1025/Cloning-Elements-with-JavaScript

使用JavaScript克隆元素相关推荐

  1. 如何使用JavaScript更改元素的类?

    如何使用JavaScript更改HTML元素的类以响应onclick事件? #1楼 对以前的正则表达式的一些小注释和调整: 如果班级列表中的班级名称不止一次,您将希望在全局范围内执行此操作. 而且,您 ...

  2. Javascript通过元素id和name直接获取元素

    概览: 偶然的机会,我在JavaScript中直接用HTML元素的id属性来获取该元素,并设置该元素的其他属性值,竟然能够正确解析不报错!于是我去查阅相关资料,也有其他同行这么用. 虽然说这种用法不是 ...

  3. 在一个div后面追加html,javascript div元素后追加节点

    例子解释: 这段代码创建新的 元素: var para=document.createElement("p"); 如需向 元素添加文本,您必须首先创建文本节点.这段代码创建了一个文 ...

  4. 小折腾:JavaScript与元素间的抛物线轨迹运动

    小折腾:JavaScript与元素间的抛物线轨迹运动 这篇文章发布于 2013年12月30日,星期一,20:40,归类于 js实例. 阅读 61147 次, 今日 55 次 by zhangxinxu ...

  5. JavaScript获取元素的样式

    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 开发工具与关键技术: JS 作者:黎耀杰 ...

  6. 详细解析 JavaScript 获取元素的坐标

    随时随地技术实战干货,获取项目源码.学习资料,请关注源代码社区公众号(ydmsq666) from:https://www.cnblogs.com/dong-xu/p/7150715.html?utm ...

  7. javascript控制元素隐藏的方法

    javascript控制元素隐藏的方法是: 设置元素style属性中的display: 例如[var t = document.getElementById('test'); t.style.disp ...

  8. html 获取页面元素高度,浅谈JavaScript获取元素的大小(高度和宽度)的方法

    本篇文章给大家介绍一下JavaScript获取元素的大小(高度和宽度)的方法.有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助. 在 JavaScript 中,使用下面 3 组属性可以获 ...

  9. javascript中元素的scrollLeft和scrollTop属性说明

    这两个属性的适用范围: 注意: 这两个属性只能用于元素设置了overflow的css样式中.否则这两个属性没有任何意义. 且overflow的值不能为visible,但可以为hidden,auto,s ...

最新文章

  1. Uber无人车收购MightyAI:掘金尚未暴富,卖水先获财务自由
  2. webpart template
  3. 开发VUE使用第三库,发现有bug怎么办?
  4. cnn卷积核参数如何确定_如何确定肉脯软塑包装的热封参数?
  5. 接口压测_Locust接口压测和插入集合点实战
  6. nginx 配置文件详解 深入理解nginx配置文件
  7. js中eval的用法
  8. 大一计算机期末考试高数试卷,大一高数期末考试试题
  9. 做好固定资产管理,提升行政的工作绩效
  10. Linux安装Nexus3
  11. Qt - 一文理解QThread多线程(万字剖析整理)
  12. python extract_convert.py对应代码解读抽取式提取+生成式提取摘要代码解读------摘要代码解读1
  13. 一级域名、二级域名、三级域名区分
  14. php坏处,cpu超频有什么坏处
  15. 我被一只老鼠的吱吱声吵醒了
  16. SpringBoot测试类不需要加@RunWith?
  17. 基于STM32F103单片机的智能扫地机器人 循迹避障车 原理图PCB设计
  18. 介绍120 个相见恨晚的神器网站--学习、搜索、图片、视频样样不少!
  19. 什么是数字式KVM远程管理功能
  20. 微信小程序点击按钮弹出弹窗_微信小程序带图片弹窗简单实现

热门文章

  1. 国密SSL证书正式上线,知道创宇云防御助力金融和重要领域完成国密升级改造...
  2. 2021北航计算机考研人数,惊了!2021考研人数422万?!淘汰率或超过70%?8所高校报考人数汇总...
  3. sqldbx解决中文乱码“????“
  4. ie禁用java怎么办,您如何解决IE中禁用javascript的问题?
  5. @Retryable @Backoff @Recover 重试注解的使用
  6. 运行supervisorctl错误提示【FATAL或BACKOFF 】Exited too quickly (process log may have details)问题总结
  7. shell连接CentOS启动可视化界面startx
  8. python查看cpu温度_Python如何读取CPU和GPU的温度?
  9. Java中有理数类Rational Number详解
  10. SpringBoot+WebSocket问题:Failed to register @ServerEndpoint class