Parse an HTML string with JS

后端 未结 10 1243
逝去的感伤
逝去的感伤 2020-11-21 07:17

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.

10条回答
  •  你的背包
    2020-11-21 07:47

    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 Test. 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.

    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

提交回复
热议问题