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.
const parse = Range.prototype.createContextualFragment.bind(document.createRange());
document.body.appendChild( parse('Today is:
') ),
document.body.appendChild( parse(`${new Date()}
`) );
Node
s 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
');
- 热议问题