Useful jQuery element creation technique

Here is a jQuery technique which John Resig once used in a workshop. It really saves time and there is no noticeable overhead when using this than others - although I haven't ran any speed tests; perhaps someone else would like to do that?

Rather than doing the following:

jQuery('<div class="foo">bar</div>');  

You can do this:

jQuery('<div />', {  
    "class": "foo",
    text: "bar"
});

Although it may not seem worth it in this example, it certainly helps when you want to add a bunch of extra attributes and click events:

jQuery('<span />', {  
    'class': 'foo',
    text: 'bar',
    click: function() {
        alert('Hello world!');
    }
});

If you're creating a lot of standard templates then you should use a templating engine. At Blue Bay, we're using mustache.js which we thought was quick, however it seems that Twitters hogan.js is apparently a lot faster and something I plan on looking into at a later date.


comments powered by Disqus