Reputation: 4142
If I do:
let html = `<!DOCTYPE html>
<html>
<head>
<title>Hello, world!</title>
</head>
<body>
<p>Hello, world!</p>
</body>
</html>`;
let newHTMLDocument = document.implementation.createHTMLDocument().documentElement;
newHTMLDocument.innerHTML = html;
console.log( newHTMLDocument );
The output is:
<html>
<head>
<title>Hello, world!</title>
</head>
<body>
<p>Hello, world!</p>
</body>
</html>
Why isn't the doctype tag included? What do I need to do so that when I output newHTMLDocument, it includes the doctype tag?
Upvotes: 1
Views: 2041
Reputation: 3980
You can also use createDocumentType()
with createHTMLDocument()
or createDocument()
:
const doc = document.implementation.createHTMLDocument('title');
console.log('before', new XMLSerializer().serializeToString(doc));
const docType = document.implementation.createDocumentType('qualifiedNameStr', 'publicId', 'systemId');
doc.doctype.replaceWith(docType);
console.log('after', new XMLSerializer().serializeToString(doc));
Upvotes: 1
Reputation: 65806
.documentElement
returns the <html>
element (the element at the root of the document - - <!doctype>
is not an element, it's a declaration node), so you are excluding the doctype
yourself.
If you get rid of .documentElement
, the doctype
remains.
let html = `<!doctype html>
<html>
<head>
<title>Hello, world!</title>
</head>
<body>
<p>Hello, world!</p>
</body>
</html>`;
let newHTMLDocument = document.implementation.createHTMLDocument();
newHTMLDocument.innerHTML = html;
// You can access the doctype as an object:
console.log("The <!doctype> is a node type of: " +newHTMLDocument.doctype.nodeType,
"\nWhile the documentElement is a node type of: " + newHTMLDocument.documentElement.nodeType);
console.log(newHTMLDocument.doctype);
alert(newHTMLDocument.innerHTML);
Upvotes: 4