Skip to content

Instantly share code, notes, and snippets.

@z-------------
Created October 9, 2019 06:21
Show Gist options
  • Save z-------------/c3bb3bf7d6308c336172c5c2ebcd3100 to your computer and use it in GitHub Desktop.
Save z-------------/c3bb3bf7d6308c336172c5c2ebcd3100 to your computer and use it in GitHub Desktop.
/**
* Create an element with supplied attributes and contents and return it
* @param {string} tagName
* @param {Object} attributes
* @param {string} attributes._text
* @param {string} attributes._html
* @param {Object<string, string>} attributes.style
* @param {Node[]} attributes._children
* @param {string} attributes.*
* @returns {HTMLElement}
*/
const makeElem = (tagName, attributes) => {
let elem = document.createElement(tagName)
for (let attributeName in attributes) {
if (["_children", "_text", "_html", "style"].indexOf(attributeName) === -1) {
elem.setAttribute(attributeName, attributes[attributeName])
}
}
if (attributes._children) {
for (let child of attributes._children) elem.appendChild(child)
} else if (attributes._text) {
elem.textContent = attributes._text;
} else if (attributes._html) {
elem.innerHTML = attributes._html;
}
if (attributes.style) {
for (let property in attributes.style) {
elem.style[property] = attributes.style[property]
}
}
return elem
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment