I searched for a solution but nothing was relevant, so here is my problem:
I want to parse a string which contains HTML text. I want to do it in JavaScript.
EDIT: The solution below is only for HTML "fragments" since html,head and body are removed. I guess the solution for this question is DOMParser's parseFromString() method.
For HTML fragments, the solutions listed here works for most HTML, however for certain cases it won't work.
For example try parsing
. This one won't work on the div.innerHTML solution nor DOMParser.prototype.parseFromString nor range.createContextualFragment solution. The td tag goes missing and only the text remains.Test
Only jQuery handles that case well.
So the future solution (MS Edge 13+) is to use template tag:
function parseHTML(html) {
var t = document.createElement('template');
t.innerHTML = html;
return t.content.cloneNode(true);
}
var documentFragment = parseHTML('Test ');
For older browsers I have extracted jQuery's parseHTML() method into an independent gist - https://gist.github.com/Munawwar/6e6362dbdf77c7865a99