DJ Quilter

Front-End Developer

Creating Elements Elegantly with jQuery

Sometime last year, I was shown that this simple bit of jQuery:

var elem = $('<div/>');

If you don’t know (or can’t guess), this is a simple way of creating a matching (ie opening and closing) set of HTML tags which you can add to the DOM whenever you need to. Previously, I was writing out my HTML in strings and then appending that to the document. Though it’s still a way of getting the job done, the above line of jQuery looks alot better.

As useful as that was to me at the time, I’ve recently seen some extensions of this on Coderwall:

var $elem = $('<div/>', {
  "class" : "some-class",
  "attr" : "value",
  "text" : "text content",      // equivalent to .text()
  "html" : "<h3>title</h3>",    // equivalent to .html()
  "click" : function() { }      // click event

I’ve seen a couple of different versions, but the above is by far the most complete. You can see adding classes and attributes is simple, as are events and child elements.

I can’t really take credit for this, it’s the work of Alex Cheuk. Still, I thought it was useful enough to put up here for my own memory if nothing else!