Last active
February 9, 2024 15:23
-
-
Save Snugug/72b80b5b3d93f4286c49ec9da3439fbc to your computer and use it in GitHub Desktop.
A little helper function to create an element with relevant attributes and optional nesting. Should be a fairly easy replacement for using innerHTML where that's not reasonable.
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
// Create an element with attributes, and optionally append children to it | |
// Public Domain licensed, if you're interested. | |
function e( | |
elm: string, | |
attrs: Record<string, string> = {}, | |
...children: (string | Node)[] | |
): Node { | |
// Create element and add relevant attributes | |
const elem = document.createElement(elm); | |
for (const [k, v] of Object.entries(attrs)) { | |
if (k === 'class') { | |
elem.className = v | |
} else { | |
elem.setAttribute(k, v) | |
} | |
} | |
// Append children | |
for (const child of children) { | |
// If a child is a string, create a text node | |
if (typeof child === 'string') { | |
elem.appendChild(document.createTextNode(child)); | |
} else { | |
// Otherwise, append the child node | |
elem.appendChild(child); | |
} | |
} | |
// Return the parent element | |
return elem; | |
} | |
// Usage | |
e('div', { class: 'foo' }, | |
'hello', | |
e('p', {}, | |
'world', | |
e('span', {}, | |
'!!!' | |
)), | |
e('p', {class: 'bar'}, | |
'world', | |
) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment