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