Skip to content

Instantly share code, notes, and snippets.

@artulloss
Last active July 10, 2021 02:13
Show Gist options
  • Save artulloss/43869e4a2e7ea9ce880f6a02ff8341e0 to your computer and use it in GitHub Desktop.
Save artulloss/43869e4a2e7ea9ce880f6a02ff8341e0 to your computer and use it in GitHub Desktop.
Simple HTML in JS
// 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>
`);
Copy link

ghost commented Jul 10, 2021

This is poggers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment