Mr eel
Prototype DOM Builder Gets Nice!
Prototype 1.5 now includes a DOM builder, which is awesome because I can now ditch my own little extensions to the library. The reason I’m happy about this is that I can make my own libraries which depend on Prototype, without having to also include my own DOM Builder lib. I can just depend on Prototype’s. Nice!
As nice as the builder is, I’m not too keen on the syntax. It makes sense, but it’s not all that nice. Too verbose for my tastes. Here’s an example:
new Element('a', {href:'/posts/1'})
Now that’s pretty nice, but if I’m coding some nice, degradable widgets, I might be creating a whole bunch of nodes. Soon enough that’d get annoying. But for me the real downside to this syntax is there is no way to nest nodes as you create them. Instead you have to do something like:
var anchor = new Element('a')
anchor.appendChild(document.createTextNode('weeeeeeee')
All that just to create an anchor with text? It’s nicer than the default DOM methods, but not as nice as it could be. So I’ve created my own extension to the Builder. Firstly it gives us a shortcut; $E(). Secondly it lets us nest elements as we create them and it automatically handles creation of text nodes. Here it is in it’s entirety
var $E = function(tag, content, options) {
if (tag == 'text') return document.createTextNode(content);
if (!options) options = {};
var element = new Element(tag, options);
if (content) {
if (content.constructor == Array) {
for (var i=0; i < content.length; i++) {
if (typeof content[i] == 'string') content[i] = $E('text', content[i]);
element.appendChild(content[i]);
};
}
else {
if (typeof content == 'string') content = $E('text', content);
element.appendChild(content);
}
}
return element;
};
Some example usage:
$E('a', 'weeeeeee', {className:'hotHotLink'})
$E('ul', $E('li', 'this is the li content'))
Comments