Last active
August 29, 2015 14:20
-
-
Save emanuelpessoaa/d348384dcaac41df26b4 to your computer and use it in GitHub Desktop.
Javascript anonymous function expression creates the specified HTML element with attributes and contents.
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
/** | |
* createElement - creates the specified HTML element with attributes and contents. | |
* @param {HTML ELEMENT} | |
* @param {ATTRIBUTE} | |
* @param {CONTENT} | |
* @return {ELEMENT} | |
* | |
* Usage: createElement("h1","[style:color:#fff;background:#000;][class:myClass][id:myId]", "My Title"); | |
*/ | |
var createElement = function(element, attribute, inner) { | |
if (typeof(element) === "undefined") { | |
return false; | |
} | |
if (typeof(attribute) === "undefined") { | |
attribute = ""; | |
} | |
if (typeof(inner) === "undefined") { | |
inner = ""; | |
} | |
var el = document.createElement(element); | |
if (attribute.length > 1 && attribute[0] == "[" && attribute[attribute.length - 1] == "]") { | |
var attr = attribute.split("]["); | |
attr[0] = attr[0].substr(1); | |
attr[attr.length - 1] = attr[attr.length - 1].substr(0, attr[attr.length - 1].length - 1); | |
for (var k = 0, len = attr.length; k < len; k++) { | |
var el_attr, el_attr_val = "", | |
ind = attr[k].indexOf(":"); | |
if (ind > 0) { | |
el_attr = attr[k].substr(0, ind); | |
el_attr_val = attr[k].substr(ind + 1); | |
} else { | |
el_attr = attr[k].substr(0); | |
} | |
el.setAttribute(el_attr, el_attr_val); | |
} | |
} | |
if (Array.isArray(inner)) { | |
for (var k = 0; k < inner.length; k++) { | |
if (inner[k].tagName) { | |
el.appendChild(inner[k]); | |
} else { | |
el.appendChild(document.createTextNode(inner[k])); | |
} | |
} | |
} else { | |
if (inner.tagName) { | |
el.appendChild(inner); | |
} else { | |
el.innerHTML = inner; | |
} | |
} | |
return el; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment