看起来,DOMParser使用innerHTML向DOM添加字符串化元素。使用它有什么好处?
我在下面比较了使用DOMParser().parseFromString()和使用element.innerHTML之间的区别。我是不是忽略了什么?
使用 DOMParser
const main = document.querySelector('main');
const newNodeString = '<body><h2>I made it on the page</h2><p>What should I do now?</p><select name="whichAdventure"><option>Chill for a sec.</option><option>Explore all that this page has to offer...</option><option>Run while you still can!</option></select><p>Thanks for your advice!</p></body>';
// Works as expected
let newNode = new DOMParser().parseFromString(newNodeString, 'text/html');
let div = document.createElement('div');
console.log('%cArray.from: ', 'border-bottom: 1px solid yellow;font-weight:1000;');
Array.from(newNode.body.children).forEach((node, index, array) => {
div.appendChild(node);
console.log('length:', array.length, 'index: ', index, 'node: ', node);
})
main.appendChild(div);使用 innerHTML
const main = document.querySelector('main');
const newNodeString = '<h2>I made it on the page</h2><p>What should I do now?</p><select name="whichAdventure"><option>Chill for a sec.</option><option>Explore all that this page has to offer...</option><option>Run while you still can!</option></select><p>Thanks for your advice!</p>';
// Works as expected
let div = document.createElement('div');
div.innerHTML = newNodeString;
main.appendChild(div);我希望DOMParser().parseFromString()提供一些我不知道的额外功能。
发布于 2019-05-27 00:50:00
嗯,首先,DOMParser可以解析XML文件。它还验证了XML的格式是否良好,如果没有,则会产生有意义的错误。更重要的是,它是使用正确的工具,为正确的工作。
我过去曾使用它来获取上传的XML文件,并使用预定义的XSLT样式表生成HTML,而没有涉及到服务器。
显然,如果您所做的只是将字符串附加到现有的DOM中,并且innerHTML (或outerHTML)为您工作,那么请继续使用它。
https://stackoverflow.com/questions/56318353
复制相似问题