I'm looking for the best way to handle parsing HTML or XHTML (XML serialized) markup and inserting it into the DOM of a webpage which could either be text/html or application/xhtml+xml. Not looking to use libraries like jQuery and really only care about compatibility with the latest version of Chrome.
I see two possible solutions.
Template & innerHTML:
let temp = document.createElement('template'); temp.innerHTML = markuptext; document.body.appendChild(temp.content);
DOMParser:
let parser = new DOMParser(); let doc = parser.parseFromString('<div xmlns="http://www.w3.org/1999/xhtml">' + markuptext + '</div>', 'application/xhtml+xml'); let frag = document.createDocumentFragment(), childNode; while (childNode = doc.documentElement.firstChild) { frag.appendChild(childNode); } document.body.appendChild(frag);
I was hoping someone could point out the advantages/disadvantages of these two approaches.
With Template & innerHTML I am assuming Chrome will choose to parse as HTML/XML depending on the content type of the page and there is probably no way to change that. It seems Template & innerHTML allows fragments like <tr><td></td></tr>
outside of a <tbody>
regardless of if it is parsing as HTML or XML. DOMParser allows this too but only if it is parsing as XML.