Skip to content

Instantly share code, notes, and snippets.

@victornpb
Created April 23, 2014 03:32
Show Gist options
  • Save victornpb/11201998 to your computer and use it in GitHub Desktop.
Save victornpb/11201998 to your computer and use it in GitHub Desktop.
Function to template DOM tags
//create element
function tag(tag, attributes, childs){
function isArray(o) {
return Object.prototype.toString.call(o) === "[object Array]";
}
function isElement(o) {
return !!(o && o.nodeType == 1);
}
function isTextNode(o) {
return o.nodeType == 3;
}
function isObject(o){
return typeof o==='object' && o!=null;
}
var element=document.createElement(tag);
if(isObject(attributes)){
for(var attName in attributes){
var attValue=attributes[attName];
if(attName.toLowerCase()=='style'){ element.style.cssText=attValue; }
else if(attName.toLowerCase()=='class' || attName.toLowerCase()=='classname'){ element.className=attValue; }
else{ element[attName] = attValue; }
}
}
if(typeof childs=="string"){
element.innerHTML = childs;
}
else{
if(isArray(childs)){
for(var i=0; i<childs.length; i++)
if(isElement(childs[i]) || isTextNode(childs[i]))
element.appendChild(childs[i]);
else if(typeof childs=="string")
element.appendChild(document.createTextNode(summary));
}
else{
for(var i=2; i<arguments.length; i++)
if(isElement(arguments[i]) || isTextNode(arguments[i]))
element.appendChild(arguments[i]);
else if(typeof arguments[i]=="string")
element.appendChild(document.createTextNode(summary));
}
}
return element;
}
/*
Examples
var myDiv = tag("div",{id:"d1", class:"c1"});
var myInput = tag("input", {type:"text", id:"name", placeholder:"Your Name here", maxlength:"20"});
var li = tag("li", {className: "recentpost"}, [
tag("div", {className: "thumb"},
tag("a", {href: link},
tag("img", {src: thumb})
)
),
tag("div",{className: "description"},
tag("h1", {},
tag("a", {href: link}, title)
),
document.createTextNode(summary)
)
]);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment