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

6
我正在将文本节点添加到文档片段中,方法如下:

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

这是有效的,但有时我会收到包含内联链接的“文本”,如下所示:

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

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

问题:
如何将类似以上的HTML字符串附加到documentFragment中?如果我不使用textNodes,是否可以使用appendChild完成?


1
你可以创建一个 div 标签并使用 innerHTML。 - some
无法这样做,因为它需要通过我的处理程序运行,该处理程序仅创建文档片段。 - frequent
innerHTML只返回字符串吗?不是的。那么为什么你假设outerHTML也是这种情况呢? - CBroe
@CBroe outerHTMLinnerHTML 返回一个 字符串。该字符串可以是 <a href='http://stackoverflow.com/'>Stack overflow</a>,但仍然是一个 字符串。证明:var a=document.createElement('div'); a.innerHTML = "<a href='http://stackoverflow.com/'>Stack overflow</a>"; console.log('The types are: %s %s', typeof a.innerHTML, typeof a.outerHTML);。类型是什么?字符串和字符串。 - some
我也考虑过和你类似的方法——创建一个DIV,将其附加到片段中,然后用div.outerHTML="…"替换该DIV(这样可以节省循环中添加子元素的时间)……但是这种方法在跨浏览器时似乎不起作用,所以你的方法看起来更可靠。 - CBroe
显示剩余5条评论
3个回答

15
创建一个模板元素,使用.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>'));

5
document.createRange().createContextualFragment("<span>Hello World!</span>");

它返回一个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>");

小心!不规范。 - Victoria

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接