JavaScript: Copy Node to DocumentFragment

寵の児 提交于 2019-12-05 22:10:10

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

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>

Works in all major browsers and IE11.

You can create a <template> element, which is a document fragment; set .innerHTML of template element, and get .innerHTML of template element using .content property

var template = document.createElement("template");
var div = document.createElement("div");
div.innerHTML = "<p>abc</p>";
template.innerHTML = div.innerHTML;
document.body.appendChild(template.content);

You can use appendChild to add the new element to the fragment.

var div=document.createElement('div');
var fragment=document.createDocumentFragment();
div.innerHTML='…';

fragment.appendChild(div);

If you only want to inject the contents of the element into the fragment then you can iterate over the childNodes and insert them into the fragment.

div.childNodes.forEach(function(node) {
    fragment.appendChild(node);
});

Try these out for size

text = frag.appendChild( document.createTextNode( "insert text here" ) )

or

text = frag.appendChild( document.createTextNode( div.innerHTML ) )

or

text = frag.appendChild( document.createTextNode( div.textContent ) )

The text variable will hold the textnode while you have also appended the textnode all in one line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!