Last active
January 30, 2019 09:16
-
-
Save jsejcksn/7d23d2f894dee69818bb85c1c151fb41 to your computer and use it in GitHub Desktop.
A function for creating an element with its content and attributes
This file contains hidden or 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
'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