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. grafana绘制动态dashboard
  2. 关于时钟、中断的理解
  3. [翻译 EF Core in Action 2.1] 设置一个图书销售网站的场景
  4. python php perl,python 调用 php 范例
  5. 漫画 | 为什么 MySQL 数据库要用 B+ 树存储索引?
  6. 面试系列-Java面试总则
  7. python 学习day3
  8. OpenGL ES简介(一)
  9. 使用Opencv分离图像通道/合并图像通道
  10. centos安装python3_CentOS安装Python3-阿里云开发者社区
  11. 分支程序设计03 - 零基础入门学习C语言12
  12. 谷歌网页存储为pdf或图片
  13. android 判断版本执行,Android版本判断
  14. 计算机组成原理实验:微程序控制实验
  15. Ubantu18.04 安装qq
  16. Evernote和印象笔记的注册问题
  17. 解决谷歌、qq、edge、360、火狐浏览器打不开Axure原型图问题
  18. Python报错 TypeError: super(type, obj): obj must be an instance or subtype of type
  19. UML在md中的写法与示意
  20. Java基础之刨根问底第6集——集合与List

热门文章

  1. 3GPP TS EPC与5GC相关协议
  2. 计算机室内设计cad实践报告,cad室内设计实习报告
  3. 软件测试课程设计——智云云盘
  4. uni-app 和H5页面视频播放flv格式视频监控
  5. Mac系统运行“exe”文件最简单的解决办法
  6. react大数据量渲染_React大量数据渲染的绝佳解决方案——React虚拟化组件
  7. 苹果录屏功能没有声音_手机录屏没有声音如何处理?可以从这三个方面入手看看...
  8. 深入浅出SSD 学习笔记整理——Johnathan Sung
  9. 关于容器和容器运行时的那些事
  10. 关于Excel自定义TEXTJOIN函数、SWITCH函数