Parse an HTML string with JS

后端 未结 10 1281
逝去的感伤
逝去的感伤 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:34

    The fastest way to parse HTML in Chrome and Firefox is Range#createContextualFragment:

    var range = document.createRange();
    range.selectNode(document.body); // required in Safari
    var fragment = range.createContextualFragment('

    html...

    '); var firstNode = fragment.firstChild;

    I would recommend to create a helper function which uses createContextualFragment if available and falls back to innerHTML otherwise.

    Benchmark: http://jsperf.com/domparser-vs-createelement-innerhtml/3

提交回复
热议问题