Skip to content

Commit

Permalink
fix: [#1615] DOMParser creating body twice
Browse files Browse the repository at this point in the history
  • Loading branch information
OlaviSau committed Nov 18, 2024
1 parent 7914b54 commit 15e6d75
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 1 deletion.
5 changes: 4 additions & 1 deletion packages/happy-dom/src/dom-parser/DOMParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,15 @@ export default class DOMParser {
const root = <DocumentFragment>XMLParser.parse(newDocument, string, { evaluateScripts: true });
let documentElement = null;
let documentTypeNode = null;
let bodyElement = null;

for (const node of root[PropertySymbol.nodeArray]) {
if (node['tagName'] === 'HTML') {
documentElement = node;
} else if (node[PropertySymbol.nodeType] === NodeTypeEnum.documentTypeNode) {
documentTypeNode = node;
} else if (node['tagName'] === 'BODY') {
bodyElement = node;
}

if (documentElement && documentTypeNode) {
Expand Down Expand Up @@ -76,7 +79,7 @@ export default class DOMParser {
default:
{
const documentElement = newDocument.createElement('html');
const bodyElement = newDocument.createElement('body');
bodyElement = bodyElement ?? newDocument.createElement('body');
const headElement = newDocument.createElement('head');

documentElement.appendChild(headElement);
Expand Down
6 changes: 6 additions & 0 deletions packages/happy-dom/test/dom-parser/DOMParser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import DOMParser from '../../src/dom-parser/DOMParser.js';
import DOMParserHTML from './data/DOMParserHTML.js';
import { beforeEach, describe, it, expect } from 'vitest';
import DOMParserSVG from './data/DOMParserSVG';
import DOMParserBODY from './data/DOMParserBODY';

describe('DOMParser', () => {
let domParser: DOMParser;
Expand Down Expand Up @@ -104,5 +105,10 @@ describe('DOMParser', () => {
DOMParserSVG.replace(/[\s]/gm, '')
);
});

it('recognises BODY', () => {
const newDocument = domParser.parseFromString(DOMParserBODY, 'text/html');
expect(newDocument.body.innerHTML).toBe('<example></example>Example Text');
});
});
});
1 change: 1 addition & 0 deletions packages/happy-dom/test/dom-parser/data/DOMParserBODY.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default '<body><example></example>Example Text</body>';

0 comments on commit 15e6d75

Please sign in to comment.