首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >DOMParser().parseFromString()值得使用吗?

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

Stack Overflow用户
提问于 2019-05-27 00:22:52
回答 1查看 8.6K关注 0票数 7

扩展

看起来,DOMParser使用innerHTML向DOM添加字符串化元素。使用它有什么好处?

我在下面比较了使用DOMParser().parseFromString()和使用element.innerHTML之间的区别。我是不是忽略了什么?

使用 DOMParser

代码语言:javascript
复制
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

代码语言:javascript
复制
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()提供一些我不知道的额外功能。

EN

回答 1

Stack Overflow用户

发布于 2019-05-27 00:50:00

嗯,首先,DOMParser可以解析XML文件。它还验证了XML的格式是否良好,如果没有,则会产生有意义的错误。更重要的是,它是使用正确的工具,为正确的工作。

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

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56318353

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档