rolfen
8/20/2017 - 12:13 PM

Lean function to generate html from JavaScript and do some of the nice things that React allows.

Lean function to generate html from JavaScript and do some of the nice things that React allows.

/**
 * Generates html element based on a d-structure
 * d-structure is:
 * [ string tagname | HtmlElement root_element,
 *	 object attributes, 
 *   [child] | string text,
 *   funcion callback(el)
 * ]
 * child is:
 * d-structure | string text | HtmlElement element
 *
 * a tagname or root_element needs to be provided. All other properties can be null
 *
 * @param d "d-structure" Array
 * @return HTMLElement
 */


function html(d) {

	// HTML tag
	var el;
	if(typeof d[0] == "string") {
		el = document.createElement(d[0]);
	} else {
		el = d[0];
	}

	// attributes
	var attributes = d[1];
	if(attributes !== null && typeof attributes === 'object') {
		for(attrName in attributes) {
			if(attributes.hasOwnProperty(attrName)) {
				var attrVal = attributes[attrName];
				el.setAttribute(attrName, attrVal);
			}
		}
	}

	// children
	if(typeof d[2] == "string") {
		var children = [d[2]];
	} else {
		var children = d[2];
	}

	if(children instanceof Array) {
		children.forEach(function(child){
			if(child instanceof Array) {
				// Curse yourself!
				el.appendChild(html(child));
			} else if(typeof child == "string") {
				// Violets are green; append text node
				el.appendChild(document.createTextNode(child));
			} else {
				// Roses are blue! We assume it's an element
				// What else could it be?
				el.appendChild(child);
			}
		});
	}

	// callback
	if(typeof d[3] == "function") {
		d[3](el);
	}

	return(el);
}