1

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?

GTS Joe
  • 3,612
  • 12
  • 52
  • 94

2 Answers2

4

.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);
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • I tried your code but if I do a console.log(newHTMLDocument); it doesn't contain my elements, title tag and p tag. I need all of my elements in an object because I'm going to be using some JS DOM functions on the object. – GTS Joe Mar 25 '18 at 02:13
  • @GTSJoe newHTMLDocumemt is an object, you don’t log it directly. My code logs it’s .innerHTML. You can get any of its contents with newHTMLDocument.querySelector(), for example. – Scott Marcus Mar 25 '18 at 02:34
  • For reference, I ended up using this answer: https://stackoverflow.com/questions/8227612/how-to-create-document-objects-with-javascript/13222848#13222848 which uses createHTMLDocument doc.open(); doc.write(html); doc.close(); to create an HTML object – GTS Joe Mar 25 '18 at 02:48
1

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));
Steven Vachon
  • 3,814
  • 1
  • 30
  • 30