jQuery: create elements the right way

jQuery is full of surprises. The $() wrapper, in particular, is more flexible than one could expect. When we create elements on the fly, this wrapper accepts an object literal as its second argument where we can specify attributes and content of the newly created element. This is a really useful feature when we want to write a more concise and compact code. Let's see the details.

Suppose that you want to create the following DOM structure:

<div id="test" class="foo">Test</div>

You can write the following:

$('<div/>', {
  id: 'test',
  'class': 'foo',
  text: 'Test'
 }).appendTo('body');

The only thing to bear in mind is that you have to write the attribute class with quotes or some browsers will return an error because this attribute is also a reserved word in ECMAScript.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

One thought on “jQuery: create elements the right way”

Leave a Reply

Note: Only a member of this blog may post a comment.