participator
participator

Reputation: 342

Is DOMParser().parseFromString() worth using?

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

It looks like the DOMParser uses innerHTML to add stringified elements to the DOM. What's the advantage of using it?

I have compared the difference between using DOMParser().parseFromString() and using element.innerHTML below. Am I overlooking something?

Using 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);

Using 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);

I expect that DOMParser().parseFromString() provides some additional functionality that I'm unaware of.

Upvotes: 8

Views: 15632

Answers (1)

Heretic Monkey
Heretic Monkey

Reputation: 12124

Well, for one thing, DOMParser can parse XML files. It also validates that the XML is well formed and produces meaningful errors if not. More to the point, it is using the right tool for the right job.

I've used it in the past to take an uploaded XML file and produce HTML using a predefined XSLT style sheet, without getting a server involved.

Obviously, if all you're doing is appending the string to an existing DOM, and innerHTML (or outerHTML) works for you, continue using it.

Upvotes: 3

Related Questions