JavaScript:将节点复制到DocumentFragment [英] JavaScript: Copy Node to DocumentFragment

查看:116
本文介绍了JavaScript:将节点复制到DocumentFragment的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为DocumentFragment的重点是能够在不接触DOM的情况下构建内容,直到它准备就绪。

I gather that the whole point of a DocumentFragment is to be able to construct the contents without touching the DOM until it’s ready to go.

鉴于DocumentFragment没有' t支持 innerHTML ,它可能有点乏味。另一方面,一旦构造,很容易通过片段本身将内容添加到现有DOM节点。

Given that DocumentFragment doesn’t support innerHTML, it can be a bit tedious. On the other hand, once constructed, it’s easy to add the contents to an existing DOM node by the fragment itself.

如果我创建 div 如果不将它添加到DOM,我可以按照我喜欢的方式填充它,包括 innerHTML 。据我所知,它应该对性能没有额外的影响。

If I create a div without adding it to the DOM, I can populate it how I like, including innerHTML. As far as I can tell, it should have no additional impact on performance.

是否有一种简单的方法(即在一行左右)复制一个内容现有DOM节点到DocumentFragment?该过程如下所示:

Is there a simple way (ie in one line or so) to copy the contents of an existing DOM node to a DocumentFragment? The process would look like:

var div=document.createElement('div');
var fragment=document.createDocumentFragment();
div.innerHTML='…';
//  copy contents to fragment
//  etc

这样我就可以两全其美。

This way I could have the best of both worlds.

回答

以下是答案以下@KevBot结合到示例中:

Here is the answer by @KevBot below incorporated into the example:

var divTest=document.querySelector('div#test');

var html='<p>One</p><p>Two</p>';
var fragment=document.createRange().createContextualFragment(html);

divTest.appendChild(fragment);


推荐答案

是的,你可以轻松地创建一个带有字符串的片段HTML使用 document.createRange 方法。

Yes, you can easily create a fragment with a string of HTML using the document.createRange method.

document.createRange 返回 范围 对象,其中有一个名为 createContextualFragment 允许您从HTML获取片段。

document.createRange returns a Range object, which has a method called createContextualFragment which allows you to get a fragment from just HTML.

function fragmentFromString(strHTML) {
  return document.createRange().createContextualFragment(strHTML);
}

let div = document.createElement('div');
div.innerHTML = '<p>Testing</p>';

let fragment = fragmentFromString(div.innerHTML);
console.log(fragment);

<div>
  <p>Random Content</p>
</div>

适用于所有主流浏览器和IE11。

Works in all major browsers and IE11.

这篇关于JavaScript:将节点复制到DocumentFragment的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆