DOMParser().parseFromString() 值得使用吗?

par*_*tor 5 javascript

https://developer.mozilla.org/en-US/docs/Web/API/DOMParser#DOMParser_HTML_extension

看起来 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);
Run Code Online (Sandbox Code Playgroud)

使用内部HTML

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);
Run Code Online (Sandbox Code Playgroud)

我希望 DOMParser().parseFromString() 提供一些我不知道的附加功能。

Her*_*key 3

嗯,一方面,DOMParser可以解析 XML 文件。它还验证 XML 的格式是否正确,如果格式错误,则会产生有意义的错误。更重要的是,它是使用正确的工具完成正确的工作。

我过去曾使用它来获取上传的 XML 文件并使用预定义的 XSLT 样式表生成 HTML,而无需涉及服务器。

显然,如果您所做的只是将字符串附加到现有 DOM,并且innerHTML(或outerHTML) 对您有用,请继续使用它。