javascript - 如何创建元素的浅拷贝?

标签 javascript jquery dom

最近在this question我问如何查明类里面是否存在风格。 (skobaljic)告诉我我需要克隆元素。在元素(jQuery 方法)的调用 .clone() 期间,生成的对象包含默认样式(例如来自样式表),因此插入的样式不包含在克隆中。我是这样理解的。但是,当我需要检测是否存在 6 种样式时,克隆完整元素(包括可能有数百或数千个子元素)似乎很奇怪。我检查了 jQuery 的克隆方法代码。有这样的:

destElements = getAll( clone );
srcElements = getAll( elem );

因此函数 getAll 被调用了两次。

然后我检查了包含 getAll 的内容:

var ret = typeof context.getElementsByTagName !== "undefined" ?
    context.getElementsByTagName( tag || "*" ) :
    typeof context.querySelectorAll !== "undefined" ?
    context.querySelectorAll( tag || "*" ) :
    [];

来自 Mozilla 手册:

The Element.getElementsByTagName() method returns a live HTMLCollection of elements with the given tag name. The subtree underneath the specified element is searched, excluding the element itself.

Document.querySelectorAll() - Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) that match the specified group of selectors. The object returned is a NodeList.

因此,很明显,创建元素的深拷贝是没有意义的,而且需要性能。当我需要进行深入搜索/比较时,这个问题会更加严重,这会导致资源的过度浪费。我想克隆没有子元素的元素。这可能吗?克隆应该包含默认样式,就像使用 .clone() 所做的那样。怎么做?

最佳答案

我相信这可以帮助你:

来源:http://www.w3schools.com/jsref/met_node_clonenode.asp

  // Copy the element and its child nodes
  var clone_with_child = yourElement.cloneNode(true);
  // Copy only the element
  var clone_without_child = yourElement.cloneNode(false);

关于javascript - 如何创建元素的浅拷贝?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39299654/

相关文章:

JavaScript:更改类指定元素的样式

jquery - 在 show() 上触发的自定义 jQuery 事件监听器

javascript - 在 D3.js 中获取圆弧的 (x,y) 坐标

javascript - 编辑按钮不起作用,请帮助如何使编辑按钮编辑值

javascript - Selenium:如何跟踪 DOM 操作以查找元素的可见性?

javascript - 动态填充列表

javascript - 将 css 动画转换为 jquery

javascript "classes"与数组跟踪器

javascript - 如何在 onclick 事件上重新加载 jquery?

javascript - 使用 DOM 显示倒计时脚本