Skip to content

Instantly share code, notes, and snippets.

@Mandrewdarts
Created October 23, 2020 22:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mandrewdarts/d0254ba03b71ec5fb75a5bbd0c961480 to your computer and use it in GitHub Desktop.
Save Mandrewdarts/d0254ba03b71ec5fb75a5bbd0c961480 to your computer and use it in GitHub Desktop.
Create Element Util
export function createElement(el = 'div', attributes = {}, innerEls = []) {
const element = document.createElement(el);
if (attributes.class) {
attributes.class.forEach((c) => element.classList.add(c));
}
if (attributes.id) {
element.id = attributes.id;
}
if (attributes.on) {
Object.entries(attributes.on).forEach(([key, value]) => {
element.addEventListener(key, value);
})
}
Object.entries(attributes)
.filter(([key, _]) => !(key === 'class' || key === 'id' || key === 'on'))
.forEach(([key, value]) => {
element.setAttribute(key, value);
});
innerEls.forEach(innerEl => {
element.append(innerEl)
})
return element;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment