Skip to content

Instantly share code, notes, and snippets.

@jsejcksn
Last active January 30, 2019 09:16
Show Gist options
  • Save jsejcksn/7d23d2f894dee69818bb85c1c151fb41 to your computer and use it in GitHub Desktop.
Save jsejcksn/7d23d2f894dee69818bb85c1c151fb41 to your computer and use it in GitHub Desktop.
A function for creating an element with its content and attributes
'use strict';
function genEl (tagName, attributes, ...childNodes) {
const el = document.createElement(tagName);
if (attributes) {
for (const [prop, value] of Object.entries(attributes)) {
if (prop === 'style' && (Array.isArray(value) || value instanceof Map)) {
for (const declaration of value) {
el.style.setProperty(...declaration);
}
}
else {
el.setAttribute(prop, value);
}
}
}
if (childNodes) {
for (let node of childNodes) {
if (typeof node === 'string') {
node = document.createTextNode(node);
}
el.appendChild(node);
}
}
return el;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment