Created
October 23, 2020 22:40
-
-
Save Mandrewdarts/d0254ba03b71ec5fb75a5bbd0c961480 to your computer and use it in GitHub Desktop.
Create Element Util
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
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