1/**
2 * String to HTMLElement and vice versa
3 */
4var stringToHtml = '<p><strong>Hello</strong>, world!</p>'
5
6/* String with HTML source code (so called DOMString) to HTMLElement */
7var elm = new DOMParser().parseFromString(stringToHtml, 'text/html')
8
9/* HTMLElement to string containing HTML source code */
10var htmlToString = new XMLSerializer().serializeToString(document.body)
11
12/**
13 * HTML source code can even be not completely valid (for example, missing
14 * close tag), it will be silently fixed
15 */
16var invalidHtmlString = '<p><strong>Hello</strong>, world!'
17console.dir(new DOMParser().parseFromString(invalidHtmlString, 'text/html'))
18
19/**
20 * Parsed HTMLElement can be safely injected into the main document
21 * context. Unlike common rough way to achieve the goal through
22 * Element.innerHTML, this method delivers the protection from XSS
23 * by default
24 */
25document.body.appendChild(elm)
26
27/**
28 * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser
29 * @see https://developer.mozilla.org/en-US/docs/Web/API/XMLSerializer
30 */