Last active
June 22, 2018 15:08
-
-
Save dantodev/09946a772eaa796665492fc500447cd5 to your computer and use it in GitHub Desktop.
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
function createElement(tagName, config) { | |
if (tagName instanceof Object) { | |
config = tagName; | |
tagName = null; | |
} | |
config = Object.assign({ | |
tagName: tagName || 'div', | |
className: null, | |
class: null, | |
attr: null, | |
events: {}, | |
target: null, | |
content: null, | |
children: [] | |
}, config || {}); | |
var element = document.createElement(config.tagName); | |
if (config.className !== null) { | |
element.className = config.className; | |
} | |
if (config.class instanceof Function) { | |
var c = {}; | |
config.class = config.class(c) || c; | |
} | |
if (Array.isArray(config.class)) { | |
element.className = config.class.join(' '); | |
} else if (config.class instanceof Object) { | |
for (var className in config.class) { | |
if (!config.class.hasOwnProperty(className)) { | |
continue; | |
} | |
if (!!config.class[className]) { | |
element.classList.add(className); | |
} | |
} | |
} | |
if (config.attr instanceof Object) { | |
for (var attr in config.attr) { | |
if (config.attr.hasOwnProperty(attr)) { | |
var value = config.attr[attr]; | |
if (value instanceof Function) { | |
value = value(); | |
} | |
if (typeof value !== "undefined") { | |
element.setAttribute(attr, config.attr[attr]); | |
} | |
} | |
} | |
} | |
for (var event in config.events) { | |
if (config.events.hasOwnProperty(event)) { | |
element.addEventListener(event, config.events[event]); | |
} | |
} | |
if (config.content !== null) { | |
element.innerHTML = config.content; | |
} else if (config.children.length > 0) { | |
config.children.forEach(function (child) { | |
if (child instanceof Object) { | |
child = createElement(child); | |
} else if (typeof child === "string") { | |
child = document.createTextNode(child); | |
} | |
if (child instanceof Node) { | |
element.append(child); | |
} | |
}); | |
} | |
if (config.target instanceof Node) { | |
config.target.appendChild(element); | |
} | |
return element; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment