Skip to content

Commit

Permalink
Skip duplicate head and body elements and keep adding to the exis…
Browse files Browse the repository at this point in the history
…ting ones

This new flag controls that no `head` or `body` element should be created while one already exists and we just add their children to the children of the existing ones instead.
  • Loading branch information
TomasHubelbauer committed Oct 13, 2024
1 parent fdb87e3 commit d3705d2
Showing 1 changed file with 15 additions and 13 deletions.
28 changes: 15 additions & 13 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,24 +131,24 @@ export default class DOMParser {
return;
}

let skipCreation = false;

if (element.tagName === 'HEAD' || element.tagName === 'head') {
if (document.head) {
reject(new Error('Only one HEAD element is allowed'));
if (!document.head) {
document.head = document.createElement('head');
document.activeElement = document.head;
}

document.head = document.createElement('head');
document.activeElement = document.head;
return;
skipCreation = true;
}

if (element.tagName === 'BODY' || element.tagName === 'body') {
if (document.body) {
reject(new Error('Only one BODY element is allowed'));
if (!document.body) {
document.body = document.createElement('body');
document.activeElement = document.body;
}

document.body = document.createElement('body');
document.activeElement = document.body;
return;
skipCreation = true;
}

// Create a `body` in case the top-level element came before `body`
Expand All @@ -162,9 +162,11 @@ export default class DOMParser {
document.activeElement = document.activeElement.parentElement;
}

const activeElement = document.createElement(element.tagName);
document.activeElement.append(activeElement);
document.activeElement = activeElement;
if (!skipCreation) {
const activeElement = document.createElement(element.tagName);
document.activeElement.append(activeElement);
document.activeElement = activeElement;
}

element.onEndTag((tag) => {
// Handle an unclosed element being followed by a closing tag for another element
Expand Down

0 comments on commit d3705d2

Please sign in to comment.