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.
Finally, somebody has it right. Thank you.