如何将 HTML 字符串附加到文档片段

How to append an HTML string to a DocumentFragment?

本文关键字:文档 片段 字符串 HTML      更新时间:2023-09-26

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

var foo = document.createDocumentFragment();
var someText = "Hello World";
foo.appendChild(document.createTextNode(someText));

这工作正常,但有时我被传递"文本",其中包含如下内联链接:

var someOtherText = "Hello <a href='www.world.com'>World</a>";

在我的处理程序中,它被转换为硬编码文本而不是链接。

问题:
如何将上述 HTML 字符串附加到文档片段中?如果我不使用textNodes可以使用appendChild来完成吗?

创建一个模板元素,添加带有.innerHTML的文本,并使用content -属性获取documentFragment

function stringToFragment(string) {
  const temp = document.createElement('template');
  temp.innerHTML = string;
  return temp.content;
}

现在你可以从字符串创建一个documentFragment,你甚至可以将一个documentFragment附加到一个documentFragment

const frag = stringToFragment('<div>Hello</div>');
frag.append(stringToFragment('<div>Stackoverflow</div>'));
document.createRange().createContextualFragment("<span>Hello World!</span>");

它返回一个文档片段。

支持 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>");

这可能有效:

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);