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

时间:2019-05-27 00:22:52

标签: 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);

使用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()提供一些我不知道的附加功能。

1 个答案:

答案 0 :(得分:0)

好,DOMParser可以parse XML files。它还可以验证XML的格式是否正确,如果不正确,则会产生有意义的错误。更重要的是,它使用正确的工具完成正确的工作。

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

很显然,如果您要做的只是将字符串附加到现有DOM,而innerHTML(或outerHTML)为您工作,请继续使用它。

相关问题