Skip to content

Instantly share code, notes, and snippets.

@vlucas
Last active May 8, 2023 20:28
Show Gist options
  • Save vlucas/de4ac7d287cff58a59cd50541b927c9e to your computer and use it in GitHub Desktop.
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
/**
* 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] +
';',
''
);
}
@vlucas
Copy link
Author

vlucas commented May 8, 2023

Usage examples:

To create an iframe:

  const mFrame = domEl('iframe', {
    id: 'myFrame',
    src: 'http://www.example.com',
    style: {
      width: `600px`,
      height: `500px`,
    },
  });

Create a wrapper div and make the iframe a child of it:

  const mContent = domEl('div', {
      id: 'frameContainer',
      style: {
        margin: '0 auto',
        border: '2px solid black',
        background: 'white',
      },
    },
    [mFrame]
  );

To append the resulting element to the of the current document:

  document.body.appendChild(mContent);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment