javascript insert html as string
/**
* String to HTMLElement and vice versa
*/
var stringToHtml = '<p><strong>Hello</strong>, world!</p>'
/* String with HTML source code (so called DOMString) to HTMLElement */
var elm = new DOMParser().parseFromString(stringToHtml, 'text/html')
/* HTMLElement to string containing HTML source code */
var htmlToString = new XMLSerializer().serializeToString(document.body)
/**
* HTML source code can even be not completely valid (for example, missing
* close tag), it will be silently fixed
*/
var invalidHtmlString = '<p><strong>Hello</strong>, world!'
console.dir(new DOMParser().parseFromString(invalidHtmlString, 'text/html'))
/**
* Parsed HTMLElement can be safely injected into the main document
* context. Unlike common rough way to achieve the goal through
* Element.innerHTML, this method delivers the protection from XSS
* by default
*/
document.body.appendChild(elm)
/**
* @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser
* @see https://developer.mozilla.org/en-US/docs/Web/API/XMLSerializer
*/