Last active
June 8, 2017 06:33
-
-
Save dennissterzenbach/615f2cd255f41c022dd071ee15b0f3e8 to your computer and use it in GitHub Desktop.
Converts a given String to DOM Nodes and adds them as children to a given parent DOM Node
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let HTMLString = `<div class="wrapper"> | |
<p>some</p> | |
<span>very fancy</span> | |
<ul> | |
<li>html</li> | |
<li>inside of</li> | |
<li>a simple</li> | |
</ul> | |
<p>String</p> | |
But we want to add this as elements to our <u>existing</u> document! | |
</div><p>Here's some paragraph</p><ul><li>oh</li><li>and a simple list</li><li>too</li></ul>`; | |
let elements = getDOMNodesFromHTMLString(HTMLString); | |
let elementsArray = Array.from(elements); | |
let contentElement = document.body; // or use document.querySelector to select the element you want to add the content to... | |
console.log('elements generated from string:', elementsArray); | |
addDOMNodes(contentElement, elements); | |
function getDOMNodesFromHTMLString(string) { | |
let div = document.createElement('div'); | |
div.innerHTML = string.trim(); | |
return div.childNodes; | |
} | |
function addDOMNodes(parentElement, nodesToAdd) { | |
nodesToAdd.forEach((item) => { | |
parentElement.appendChild(item); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment