Skip to content

Commit

Permalink
.html() send context to parse5 (#1627)
Browse files Browse the repository at this point in the history
* .html() send context to parse5

Fixes #1083

* .html() test with script element

Co-authored-by: 5saviahv <[email protected]>
  • Loading branch information
5saviahv and 5saviahv authored Jan 1, 2021
1 parent 21de2c5 commit bf04330
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 5 deletions.
4 changes: 3 additions & 1 deletion lib/api/manipulation.js
Original file line number Diff line number Diff line change
Expand Up @@ -753,13 +753,15 @@ exports.html = function (str) {
return html(this[0].children, this.options);
}

var opts = this.options;
var opts = Object.apply({}, this.options); // keep main options

return domEach(this, function (_, el) {
el.children.forEach(function (child) {
child.next = child.prev = child.parent = null;
});

opts.context = el;

var content = str.cheerio
? str.clone().get()
: parse('' + str, opts, false).children;
Expand Down
12 changes: 8 additions & 4 deletions lib/parsers/parse5.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,16 @@ var parse5 = require('parse5');
var htmlparser2Adapter = require('parse5-htmlparser2-tree-adapter');

exports.parse = function (content, options, isDocument) {
var parse = isDocument ? parse5.parse : parse5.parseFragment;

return parse(content, {
var opts = {
treeAdapter: htmlparser2Adapter,
sourceCodeLocationInfo: options.sourceCodeLocationInfo,
});
};

var context = options.context;

return isDocument
? parse5.parse(content, opts)
: parse5.parseFragment(context, content, opts);
};

exports.render = function (dom) {
Expand Down
13 changes: 13 additions & 0 deletions test/api/manipulation.js
Original file line number Diff line number Diff line change
Expand Up @@ -1611,6 +1611,19 @@ describe('$(...)', function () {
$remove.replaceWith($children);
expect($fruits.children()).toHaveLength(4);
});

it('(script value) : should add content as text', function () {
var $data = '<a><b>';
var $script = $('<script>').html($data);

expect($script).toHaveLength(1);
expect($script[0].type).toBe('script');
expect($script[0].name).toBe('script');

expect($script[0].children).toHaveLength(1);
expect($script[0].children[0].type).toBe('text');
expect($script[0].children[0].data).toBe($data);
});
});

describe('.toString', function () {
Expand Down

0 comments on commit bf04330

Please sign in to comment.