Skip to content

Instantly share code, notes, and snippets.

@danwrong
Created November 13, 2009 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save danwrong/233879 to your computer and use it in GitHub Desktop.
Save danwrong/233879 to your computer and use it in GitHub Desktop.
// DOM Builder plugin for jQuery
// (c) Dan Webb (dan@massiverobot.co.uk)
//
// $.build(function() {
//
// div({ 'class': 'module' },
// h1('A list of stuff'),
// ul(
// li('item 1'),
// li('item 2'),
// li('item 3')
// )
// );
//
// }).appendTo(document.body);
(function($) {
var flatten = function(arr) {
var res = [];
for (var i=0; i < arr.length; i++) {
var item = arr[i];
res = res.concat((item instanceof Array) ? flatten(item) : [item]);
}
return res;
};
$.dombuilder = function() {
this.parts = [];
}
$.dombuilder.functionFor = function(element) {
return function() {
var attrs, children;
if (arguments.length > 0) {
if (arguments[0].constructor == Object) {
attrs = arguments[0];
children = Array.prototype.slice.call(arguments, 1);
} else {
children = flatten(arguments);
};
}
return this.build(element, attrs, children);
}
}
$.dombuilder.prototype = {
attributes: function(attrs) {
var pairs = [];
for (var key in attrs) {
pairs.push([key, '="', attrs[key], '"'].join(''));
}
if (pairs.length == 0) return '';
else return (' ' + pairs.join(' '));
},
selfClosingTag: function(name, attrs) {
return ['<', name, this.attributes(attrs), ' />'];
},
openingTag: function(name, attrs) {
return ['<', name, this.attributes(attrs), '>'];
},
closingTag: function(name) {
return ['</', name, '>'];
},
build: function(name, attrs, children) {
attrs = attrs || {}; children = children || [];
if (children.length == 0) {
this.parts = this.selfClosingTag(name, attrs);
} else {
this.parts = [this.openingTag(name, attrs),
children, this.closingTag(name)];
}
return this.parts;
},
toString: function() {
return flatten(this.parts).join('');
}
}
$.each(("p|div|span|strong|em|img|table|tr|td|th|thead|tbody|tfoot|pre|code|" +
"h1|h2|h3|h4|h5|h6|ul|ol|li|form|input|textarea|legend|fieldset|" +
"select|option|blockquote|cite|br|hr|dd|dl|dt|address|a|button|abbr|acronym|" +
"script|link|style|bdo|ins|del|object|param|col|colgroup|optgroup|caption|" +
"label|dfn|kbd|samp|var").split("|"), function(i, el) {
$.dombuilder.prototype[el] = $.dombuilder.functionFor(el);
});
$.build = function(func) {
html = new $.dombuilder;
if (func.length == 0) {
var funcBody = func.toString().match(/^[^\{]*{((.*\n*)*)}/m)[1];
var newFunc = new Function("html", "with (html) {\n" + funcBody + "\n}");
newFunc(html);
} else func(html);
return $(html.toString());
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment