DomParser parseFromString删除节点 [英] DomParser parseFromString removing nodes

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

问题描述

使用DomParser时,我遇到了一些奇怪的行为.看来,如果第一个元素是TEMPLATE,它将被忽略.

I came across some strange behaviour when using the DomParser. It appears that if the first element is a TEMPLATE, it's ignored.

请参见以下输出:

printTags('<template></template><h1></h1>', 'text/html');
document.write('<hr>')
printTags('<h1></h1><template></template>', 'text/html');

function printTags(str)
{
	let doc = new DOMParser().parseFromString(str, 'text/html');
	document.write(Array.from(doc.body.children).map(child => child.tagName).join(','));
}

浏览器:Chrome 72

Browser: Chrome 72

这是通常的行为吗?如果是这样,我在哪里可以找到文档?

Is this usual behaviour? If so, where can I find the documentation?

推荐答案

DOMParser()将字符串中的HTML源代码解析为DOM.不确定字符串内容是否解析为body,因此请尝试使用<body>标记将其包装.

DOMParser() parse HTML source code from the string into a DOM. It's not sure that string contents parsed as body, so try wrapping it with <body> tag.

printTags('<body><template></template><h1></h1></body>', 'text/html');
document.write('<hr>')
printTags('<body><h1></h1><template></template></body>', 'text/html');

function printTags(str) {
  let doc = new DOMParser().parseFromString(str, 'text/html');
  document.write(Array.from(doc.body.children).map(child => child.tagName).join(','));
}

这篇关于DomParser parseFromString删除节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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