Anilton Q
Anilton Q

Reputation: 1

DOM nodes generate HTML5 Possible?

I want to generate a html5 file using DOM node methods, is it possible ?

I already tried making but, i can't find the right code to generate with the "!DOCTYPE" template.

I want like this structure :

<!DOCTYPE html>
........
.......
.....
...
..
</html>

Upvotes: 0

Views: 201

Answers (1)

Kaiido
Kaiido

Reputation: 137006

Sure you can generate a <doctype> node, you'll just have to use document.implementation.createDocumentType() method.

However, to generate an HTML5 document is quite a burden (at least when it comes to stringification). Indeed, there is no HTML5 namespace, and your HTML5 document is actually XHTML once parsed in the DOM:

console.log(document.documentElement.namespaceURI);

So when you'll stringify this document, you'll have the xmlns="http://www.w3.org/1999/xhtml" attributes all over your elements.

To avoid that, you actually need to generate all your elements with a null namespace:

// Our <!DOCTYPE html> node
const doctype = document.implementation.createDocumentType('html', '', ''); 
// A new HTML5 document
const doc = document.implementation.createDocument("", 'html', doctype);

// We need to force null NS
const body = doc.createElementNS(null, 'body');
body.appendChild(doc.createTextNode('hello'));

doc.documentElement.appendChild(body);

const str = (new XMLSerializer).serializeToString(doc);

console.log(str);

Upvotes: 2

Related Questions