Intuitive API:
$E('h1', 'Giant squirrel attacks Boston', { id:'myheading' })
Lightweight implementation:
Element.create = function(el){
if (typeof el == 'string') el = document.createElement(el);
Element.extend(el);
// add children (if given)
for (var i = 1, length = arguments.length; i < length; i++)
arguments.callee.add(el, arguments[i]);
return el;
}
Element.create.add = function(el, child){
if (!child) return;
var _method = arguments.callee;
switch (typeof child) {
case 'object':
if (child.nodeType) el.appendChild(child);
else if (child.constructor == Array)
child.flatten().each(function(subitem){ _method(el, subitem) });
else $H(child).each(function(pair){
el.setAttribute(pair.key, pair.value)
});
break;
case 'string':
el.appendChild(document.createTextNode(child)); break;
case 'function':
_method(el, child()); break;
}
}
var $E = Element.create;
What might not be obvious:
- flattens arrays and adds their elements
- calls functions