Last active
September 30, 2023 00:52
-
-
Save mrpapercut/dbbbe692a96db4b6dbaa84e557cef678 to your computer and use it in GitHub Desktop.
ES6-only createElement function
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
const createElement = (tagname = '') => { | |
return (...content) => { | |
const el = document.createElement(tagname); | |
if (content[0] instanceof Object && !(content[0] instanceof HTMLElement)) { | |
let attributes = content.shift(); | |
for (let attr in attributes) { | |
switch (attr) { | |
case 'events': | |
if (!(attributes[attr] instanceof Object)) { | |
throw new Error('Error: attribute "events" is not an object'); | |
} else { | |
for (let event in attributes[attr]) { | |
el.addEventListener(event, attributes[attr][event]); | |
} | |
} | |
break; | |
case 'styles': | |
if (!(attributes[attr] instanceof Object)) { | |
throw new Error('Error: attribute "styles" is not an object'); | |
} else { | |
for (let style in attributes[attr]) { | |
el.style[style] = attributes[attr][style]; | |
} | |
} | |
break; | |
case 'className': | |
attributes[attr].split(/\s/).forEach(className => el.classList.add(className)); | |
break; | |
default: | |
el.setAttribute(attr, attributes[attr]); | |
} | |
} | |
} | |
content.forEach(child => { | |
if (child instanceof HTMLElement) { | |
el.appendChild(child); | |
} else if (typeof child === 'string' || typeof child === 'number') { | |
const span = document.createElement('span'); | |
span.innerText = child; | |
el.appendChild(span); | |
} else if (Array.isArray(child)) { | |
child.forEach(c => el.appendChild(c)); | |
} else { | |
// do nothing | |
} | |
}); | |
return el; | |
} | |
} | |
export default createElement; |
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
import createElement from './createElement.js'; | |
const [div, h2, img, button] = ['div', 'h2', 'img', 'button'].map(el => createElement(el)); | |
const html = div({ | |
className: 'wrapper big' | |
}, | |
h2({ | |
styles: { | |
textDecoration: 'underline', | |
fontFamily: 'monospace' | |
} | |
}, 'Hello, world!'), | |
img({ | |
src: 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==', | |
title: 'Empty pixel' | |
}), | |
button({ | |
events: { | |
click: () => alert(1) | |
} | |
}, 'Click!'), | |
div(div(div(div('Nesting...')))) | |
); | |
document.body.appendChild(html); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment