Last active
May 8, 2023 20:28
-
-
Save vlucas/de4ac7d287cff58a59cd50541b927c9e to your computer and use it in GitHub Desktop.
Shortcut function to create a return a DOM element. Handles children, CSS via `style` attribute, and `text` and `html` attributes also
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
/** | |
* Shortcut function to create and return a DOM element | |
*/ | |
function domEl(tag: string, attributes: { [key: string]: any } = {}, children: any[] = []) { | |
const el = document.createElement(tag); | |
for (const attr in attributes) { | |
if (attr === 'text') { | |
el.appendChild(document.createTextNode(attributes[attr])); | |
continue; | |
} | |
if (attr === 'html') { | |
el.innerHTML = attributes[attr]; | |
continue; | |
} | |
if (attr === 'style') { | |
el.setAttribute('style', styleToString(attributes[attr])); | |
continue; | |
} | |
if (attributes.hasOwnProperty(attr)) { | |
el.setAttribute(attr, attributes[attr]); | |
} | |
} | |
const fragment = document.createDocumentFragment(); | |
children.forEach((child) => { | |
if (typeof child === 'string') { | |
child = document.createTextNode(child); | |
} | |
fragment.appendChild(child); | |
}); | |
el.appendChild(fragment); | |
return el; | |
} | |
function styleToString(style: any) { | |
return Object.keys(style).reduce( | |
(acc, key) => | |
acc + | |
key | |
.split(/(?=[A-Z])/) | |
.join('-') | |
.toLowerCase() + | |
':' + | |
style[key] + | |
';', | |
'' | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage examples:
To create an iframe:
Create a wrapper div and make the iframe a child of it:
To append the resulting element to the of the current document: