Skip to content

Instantly share code, notes, and snippets.

@tomhodgins
Last active September 18, 2020 02:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomhodgins/32ef08df6ecc72219b1de11e7335f6d8 to your computer and use it in GitHub Desktop.
Save tomhodgins/32ef08df6ecc72219b1de11e7335f6d8 to your computer and use it in GitHub Desktop.
// We can create a new empty HTML document
const htmlDocument = document.implementation.createHTMLDocument()
// And we can find the XML namespace of HTML (http://www.w3.org/1999/xhtml) in the browser too
const xmlns = new DOMParser().parseFromString(
new XMLSerializer().serializeToString(htmlDocument),
'text/html'
).documentElement.getAttribute('xmlns')
// Using the namespace for HTML we can create a new XML document in the HTML namespace like this
const xmlDocument = document.implementation.createDocument(xmlns, '')
// Within the context of our empty HTML document, this function will parse HTML syntax and return a document fragment containing all parsed nodes of HTML DOM
function parseAsHTML(string = '') {
return htmlDocument.createRange().createContextualFragment(string)
}
// Within the context of our empty XML document, this function will parse XML syntax and return a document fragment containing all parsed nodes of HTML DOM
function parseAsXML(string = '') {
return xmlDocument.createRange().createContextualFragment(string)
}
// In HTML syntax, 'self-closing' tags are parsed as open tags like <div><div><div>
console.log(
parseAsHTML(`<div /><div /><div />`)
)
/*
<div>
<div>
<div></div>
</div>
</div>
*/
// In XML syntax, self-closing tags truly are self closing like <div></div><div></div><div></div>
console.log(
parseAsXML(`<div /><div /><div />`)
)
/*
<div></div>
<div></div>
<div></div>
*/
// In this way, custom elements in HTML can be written as self-closing if in XML syntax, like any tag
console.log(
parseAsXML(`<custom-element /><p /><custom-element /><p />`)
)
/*
<custom-element></custom-element>
<p></p>
<custom-element></custom-element>
<p></p>
*/
// Even though this cannot be expressed in HTML syntax, since these are all parsed as open tags
console.log(
parseAsHTML(`<custom-element /><p /><custom-element /><p />`)
)
/*
<custom-element>
<p>
<custom-element></custom-element>
</p>
<p></p>
</custom-element>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment