Just realized that by default, DOMParser.parseFromString()
creates documents in Quirks mode. Is there a way to make it Standard mode?
console.log(document.compatMode) // 'CSS1Compat'
const doc = new DOMParser().parseFromString('<div>Hello World</div>', 'text/html');
console.log(doc.compatMode) // 'BackCompat'
CodePudding user response:
It looks like it will if you provide the full HTML markup including the standard doctype of <!DOCTYPE html>
. If you only provide it an HTML fragment - like <div>Hello World</div>
- rather than a full page, the engine will create a surrounding doctype and <html>
and <body>
for you, and will assume quirks mode.
console.log(document.compatMode);
const doc = new DOMParser().parseFromString(`
<!DOCTYPE html>
<html lang="en">
<body>
<div>Hello World</div>
</body>
</html>
`, 'text/html');
console.log(doc.compatMode);
CodePudding user response:
All you need to do is prepend <!DOCTYPE html>
to the HTML your parsing
DOMParser will result in the following "document"
<html>
<head>
</head>
<body>
<div>Hello World</div>
</body>
</html>
console.log(document.compatMode) // 'CSS1Compat'
const doc = new DOMParser().parseFromString('<!DOCTYPE html><div>Hello World</div>', 'text/html');
console.log(doc.compatMode) // 'BackCompat'
console.log(doc.documentElement.outerHTML)