Beautiful Element Creation with jQuery

Beautiful Element Creation with jQuery

jQuery lets you create elements and then attach an object of parameters to it. It will then use those parameters to create the element and its attributes.

//Charles the alcoholic div
$('<div />', {
id: "charles"
});

In previous versions of jQuery you would write this:

$('<div id="charles"></div>'); Now, volume-wise it appears that the second option is clearer and if you're creating a simple div with an ID, this is an excellent solution. The object-style creation has many more advantages in my opinion.

You can add events to the object.

Probably the best feature of creating this object is that you can add events to it. It's just another parameter.
$('<div />', { 	id: 'charles', 	click: function(e){ 		e.preventDefault(); 		$(this).animate({opacity: 0.7});  	} });

You can clone the crap out of it.

Having a nice object like this works like any other jQuery object.


var anchor = $('<a />', {
className: 'awesome',
href: '#',
text: "This is an anchor ",
click: function(e){
e.preventDefault();
$(this).parent().slideToggle();
}
});

$("li").each(function(){
$(this).prepend(anchor.clone());
});
You can set it to a variable and clone it when you need it. You can do this with the previous element creation syntax as well, but look at how _pretty_ that is.