Parse an HTML string with JS

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

    const parse = Range.prototype.createContextualFragment.bind(document.createRange());
    
    document.body.appendChild( parse('

    Today is:

    ') ), document.body.appendChild( parse(`

    ${new Date()}

    `) );


    Only valid child Nodes within the parent Node (start of the Range) will be parsed. Otherwise, unexpected results may occur:

    //  is "parent" Node, start of Range
    const parseRange = document.createRange();
    const parse = Range.prototype.createContextualFragment.bind(parseRange);
    
    // Returns Text "1 2" because td, tr, tbody are not valid children of 
    parse('1 2');
    parse('1 2');
    parse('1 2');
    
    // Returns , which is a valid child of 
    parse('
    1 2
    '); parse('
    1 2
    '); parse('
    1 2
    '); // is parent Node, start of Range parseRange.setStart(document.createElement('tr'), 0); // Returns [, ] element array parse('1 2'); parse(' 1 2 '); parse(' 1 2 '); parse('
    1 2
    ');

提交回复
热议问题