Last active
March 18, 2016 01:21
-
-
Save Kruithne/b45ab9244b0df0e7be6b to your computer and use it in GitHub Desktop.
Mini element builder
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
$.build = function(params) | |
{ | |
if (!params.hasOwnProperty("type")) | |
return null; | |
var element = $("<" + params.type + "/>"); | |
for (var propKey in params) | |
{ | |
if (params.hasOwnProperty(propKey)) | |
{ | |
var propValue = params[propKey]; | |
switch (propKey) | |
{ | |
case "type": | |
break; | |
case "attr": | |
case "css": | |
if (typeof(propValue) == "object") | |
element[propKey](propValue); | |
break; | |
case "events": | |
if (typeof(propValue) == "object") { | |
for (var subKey in propValue) | |
if (propValue.hasOwnProperty(subKey)) | |
element.on(subKey, propValue[subKey]); | |
} | |
break; | |
case "class": | |
if (!$.isArray(propValue)) | |
propValue = propValue.split(" "); | |
for (var i = 0; i < propValue.length; i++) | |
element.addClass(propValue[i]); | |
break; | |
case "children": | |
if (!$.isArray(propValue)) | |
break; | |
for (var c = 0; c < propValue.length; c++) | |
element.append($.build(propValue[c])); | |
break; | |
case "parent": | |
if (!(propValue instanceof jQuery)) | |
propValue = $.build(propValue); | |
propValue.append(element); | |
break; | |
default: | |
element[propKey](propValue); | |
} | |
} | |
} | |
return element; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment