Last active
July 10, 2021 02:13
-
-
Save artulloss/43869e4a2e7ea9ce880f6a02ff8341e0 to your computer and use it in GitHub Desktop.
Simple HTML in JS
This file contains hidden or 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
// Rather than writing document.createElement() to create HTML attributes, this function will do it for you | |
const html = (string, ...props) => { | |
if(props.length) { | |
let interpolatedString = ""; | |
for(let i = 0; i < string.length; i++) { | |
if(props[i] !== undefined) { | |
interpolatedString += string[i] + props[i]; | |
} else { | |
interpolatedString += string[i]; | |
} | |
} | |
string = interpolatedString; | |
} | |
const wrapper = document.createElement("div"); | |
wrapper.innerHTML = string; | |
return wrapper.childNodes.length > 1 ? wrapper.childNodes : wrapper.firstChild; | |
} | |
// Usage: | |
let name = "Adam"; | |
// Returns a NodeElement you can append to any element | |
html` | |
<div> | |
<h1>Hello ${name}!</h1> | |
</div> | |
`; | |
// No parent element needed | |
html` | |
<h1>This outputs a NodeList</h1> | |
<div> | |
<h1>Hello ${name}!</h1> | |
</div> | |
`; | |
// Finally call the Element methods append(), prepend(), before() or after(). | |
document.getElementById("myElementId").append(html` | |
<h1>Single element</h1> | |
`); | |
document.getElementById("myElementId").append(...html` | |
<h1>With</h1> | |
<h1>multiple</h1> | |
<h1>elements</h1> | |
`); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is poggers