DomParser parseFromString removing nodes

别来无恙 提交于 2019-12-20 03:17:38

问题


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

See the output of below:

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(','));
}

Browser: Chrome 72

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


回答1:


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(','));
}


来源:https://stackoverflow.com/questions/55135703/domparser-parsefromstring-removing-nodes

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