Skip to content

Instantly share code, notes, and snippets.

@Kruithne
Last active March 18, 2016 01:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kruithne/b45ab9244b0df0e7be6b to your computer and use it in GitHub Desktop.
Save Kruithne/b45ab9244b0df0e7be6b to your computer and use it in GitHub Desktop.
Mini element builder
$.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