Skip to content

Instantly share code, notes, and snippets.

@ephys
Created June 14, 2021 14:36
Show Gist options
  • Save ephys/ece80c1cd8edbb2f6182754d1260eebf to your computer and use it in GitHub Desktop.
Save ephys/ece80c1cd8edbb2f6182754d1260eebf to your computer and use it in GitHub Desktop.
function createElement(tagName, attributes) {
const element = document.createElement(tagName);
for (let attributeName of Object.keys(attributes)) {
const attribute = attributes[attributeName];
if (attributeName.startsWith('on') && typeof attribute === 'function') {
const eventName = attributeName.substr(2).toLowerCase();
element.addEventListener(eventName, attribute);
}
if (attributeName === 'className') {
attributeName = 'class';
}
if (attributeName === 'class' && Array.isArray(attribute)) {
for (const className of attribute) {
if (!className) {
continue;
}
element.classList.add(className);
}
continue;
}
if (attributeName === 'children') {
if (attribute == null) {
continue;
}
if (Array.isArray(attribute)) {
for (const child of attribute) {
if (child != null) {
element.append(child);
}
}
} else {
element.append(attribute);
}
continue;
}
element.setAttribute(attributeName, attribute);
}
return element;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment