如何将HTML字符串附加到DocumentFragment?

fre*_*ent 3 html javascript string appendchild createtextnode

我正在将textnodes添加到documentFragment中,如下所示:

var foo = document.createDocumentFragment();
var someText = "Hello World";
foo.appendChild(document.createTextNode(someText));
Run Code Online (Sandbox Code Playgroud)

这工作正常,但有时我传递"文本",其中包括这样的内联链接:

var someOtherText = "Hello <a href='www.world.com'>World</a>";
Run Code Online (Sandbox Code Playgroud)

我的处理程序中的哪个转换为硬编码文本而不是链接.

问题:
如何将上述HTML字符串附加到documentFragment中?如果我不使用,textNodes可以使用appendChild吗?

som*_*ome 9

创建一个临时div,在innerHTML中插入文本,然后将div的所有节点移动到片段.由于元素一次只能在一个位置,因此它将自动从临时div标签中删除.

var frag = document.createDocumentFragment();

var div = document.createElement('div');
div.innerHTML = '<a href="http://stackoverflow.com/">Stack overflow</a>';
while (div.firstChild) frag.appendChild(div.firstChild);
Run Code Online (Sandbox Code Playgroud)


Jor*_*dan 6

document.createRange().createContextualFragment("<span>Hello World!</span>");
Run Code Online (Sandbox Code Playgroud)

它返回一个DocumentFragment.

支持IE> = 9

编辑:

最近的版本Safari似乎以短路失败,这里有点长但工作方式:

var range = document.createRange();
range.selectNode(document.body); // Select the body cause there is always one (documentElement fail...)

var fragment = range.createContextualFragment("<span>Hello World!</span>");
Run Code Online (Sandbox Code Playgroud)


Mek*_*vez 1

这可能有效:

var foo = document.createDocumentFragment();
var someText = 'Hello <a href="www.world.com">World</a>';
var item = document.createElement('span');
item.innerHTML = someText
foo.appendChild(item);
document.body.appendChild(foo);
Run Code Online (Sandbox Code Playgroud)