Parse an HTML string with JS

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

    It's quite simple:

    var parser = new DOMParser();
    var htmlDoc = parser.parseFromString(txt, 'text/html');
    // do whatever you want with htmlDoc.getElementsByTagName('a');
    

    According to MDN, to do this in chrome you need to parse as XML like so:

    var parser = new DOMParser();
    var htmlDoc = parser.parseFromString(txt, 'text/xml');
    // do whatever you want with htmlDoc.getElementsByTagName('a');
    

    It is currently unsupported by webkit and you'd have to follow Florian's answer, and it is unknown to work in most cases on mobile browsers.

    Edit: Now widely supported

提交回复
热议问题