Creating DOM elements with a config object
Created for my answer to http://stackoverflow.com/questions/38672923/universal-function-to-create-children-elements-and-append-to-parent-nodes
by UselessCode
HTML
<ul id="list">
<li>Hardcoded item</li>
</ul>
CSS
.fancy {
color: red;
text-decoration: italic;
}
.houdini {
opacity: 0;
transition: all 2s linear;
}
.houdini.show {
opacity: 1;
}
JavaScript
'use strict';
var addNewElement = function (configItems, elParent) {
var newElements = [];
if (!Array.isArray(configItems)) {
// if configItems is not an array, and therefore a
// single config object or string, turn it into
// a single element array
configItems = [configItems];
}
// If elParent is a string assume it is
// the id of an element in the page and select it
if (typeof elParent === 'string') {
elParent = document.getElementById(elParent);
}
configItems.forEach(function (config) {
var option,
elChild;
// if a string is passed in, assume it is
// the tagName and create a default config object
if (typeof config === 'string') {
config = {tag: config};
}
elChild = document.createElement(config.tag);
for (option in config) {
if (config.hasOwnProperty(option)) {
switch (option) {
case 'tag':
// do nothing, already used tag to create new element
break;
case 'html':
// just a shortcut so we don't have to use
// innerHTML in our config object
elChild.innerHTML = config.html;
break;
case 'text':
// another shortcut
elChild.textContent = config.text;
break;
case 'class':
// if we are passed an array convert it to a space delimited string
elChild.className = Array.isArray(config.class) ?
config.class.join(' ') : config.class;
break;
default:
// if we haven't already handled it, assume it is
// an attribute to add to the element
elChild.setAttribute(option, config[option]);
}
}
}
// default text if none was specified
if (elChild.innerHTML === '') {
elChild.innerHTML = 'new element';
}
...