Skip to content

Instantly share code, notes, and snippets.

@Snugug
Last active February 9, 2024 15:23
Show Gist options
  • Save Snugug/72b80b5b3d93f4286c49ec9da3439fbc to your computer and use it in GitHub Desktop.
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.
// 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