Working daily with jQuery, at GORGES I frequently need to construct little document snippets and forms on the fly. Today I came up with a quick little meta-programming “hack” that makes this very easy and fast.
Most people simply do something along the lines of this:
$('body').append('<h1>Hello, World</h1>');
jQuery injects the HTML string into the DOM, and all is well.
But sometimes you need to inject more structured content, or even entire forms – what I typically do is something along the lines of this:
jQuery('body').append(
$('<div/>').append(
$('<div/>').text('Hi there'),
$('<p/>').text('How do you do?')
)
);
With all the parentheses, angle brackets and repetitive calls to append(), this doesn’t exactly look nice.
Recognizing the repetitive construction of elements, followed by calls to append, what if we had a set of tiny functions that would do both in one simple operation? I decided to give it a shot, and here’s what it looks like:
jQuery('body').append(
$div(
$h2('Do you love it?'),
$form(
$div('Sign here:', $text()),
$div($label($checkbox('yes'), 'I love it!')),
$ul(
$li($radio('1'), 'Option One'),
$li($radio('2'), 'Option Two'),
$li($radio('3'), 'Option Three')
),
$submit('I submit!')
)
)
);
The functions prefixed with the $-sign create the elements, and pass down any arguments to the append() method.
The input element methods, such as $radio and $submit are a bit different – they create input elements, set the type-attribute, and if you pass them an argument, they apply that as the value-attribute on the element. (input elements can’t have child-elements, so this doesn’t get in the way of anything.)
You can see a working example and source code here.
Because JavaScript is a highly dynamic language, I didn’t need to write each of these $-functions by hand – with just 13 lines of JavaScript, applying a simple meta-programming technique, all of the functions are automatically generated.
Finally, it’s worth noting that something like $('<div/>') actually results in a string of HTML being parsed and then inserted into the browser. My handy little DOM-helpers avoid the parser – they access the DOM and create HTML elements directly, which means they execute around 10 times faster compared to the first example.
Update
One of my GORGES colleagues pointed out the fact that I had no convenient way to apply attributes to the created elements – if you don’t like the repetitive calls to attr(), try this updated version, which provides a simplified way to apply attributes quickly. This takes a bit more code, but I suspect he’s now porting this to CoffeeScript

