Advantages to DOMParser vs template & innerHTML Advantages to DOMParser vs template & innerHTML google-chrome google-chrome

Advantages to DOMParser vs template & innerHTML


It depends what is your goal. If you want just append parsed html/xhtml 'as is' then go with .innerHTML, its easier and usually faster.Hovewer, from my experience, often, you have to do some kind of transformations, then using dom operations is best way. But you should avoid appending node by node to document.body in loop, because it is slow and inefficient, just create some 'dummy' dom element, add nodes to it in loop, than append whole object:

let div = document.createElement('div');let childNode;while (childNode = doc.documentElement.firstChild) {    div.appendChild(childNode);}document.body.appendChild(div);

One important note, about trying to find most efficient solutions in JS. JS performance highly depend on javascript engine, and what parts of js will be optimized in the future. So you should always write some kind of performance tests ( or use prepared test suites), especially about slow 'parts' like DOM API. Good news is that engine developers tend to favor well known solutions and 'good practices' to be optimized and they usually leave 'bad parts'.

Here are some good tests on innerHTML vs DOM append:http://andrew.hedges.name/experiments/innerhtml/

Appending to DOm without creating 'dummy' div:https://coderwall.com/p/o9ws2g/why-you-should-always-append-dom-elements-using-documentfragments

And more technical explanations about .innerHTML, .appendChild, .insertAdjacentHTML""innerHTML += ..." vs "appendChild(txtNode)"


Maybe a mixed approach?

var dom = new DOMParser().parseFromString('<template>'+ markuptext +'</template>','text/html').head;document.getElementById('my-div').appendChild(dom.firstElementChild.content);


On this page they advise the first solution which is to:

let tmpl = document.createElement('template');tmpl.innerHTML = text;shadowRoot.appendChild(tmpl.content.cloneNode(true));

https://developers.google.com/web/fundamentals/web-components/customelements