creating DOM elements with jQuery in a more elegant way
So you are dynamically creating dom elements using jQuery? Do you hate html in you javascript code as much as I do?
Does this gross you out?
$('body').html($('<div class="spinner"></div>'));
To me, this is slightly more elegant.
$('body').html($('<div>', {class: 'spinner'}));
It also makes it easier if you have dynamic properties, such as id created from a primary key, a conditional class.
Related protips:
Written by David Morrow
Related protips
13 Responses

Um, doesn't this simply work? Why create a jquery object?
$('body').html('<div class="spinner"></div>')

I think the point was to create a DOM element without writing to much html. Maybe the example is a bit misleading.

@dpashkevich yeah it does simply work, but as i was saying in my example when you have dynamic attributes I find it cleaner, personal preference.
var className = "booya";
$('body').html($('<div>', {class: className}));
pretty good...

@dperrymorrow oh ok, now I see!

just use mootools

Yeah, writing HTML in your JS is less than ideal and should be avoided. I would push for always using javascript templates. But, sometimes you find yourself in this situation.

This is far more elegant than either of those approaches.
document.body.grab(new Element('div').addClass('spinner'));

@milesj: where can I find the documentation for grab()?

Ok, I see the grab() method belongs to Mootols.

For the record, I am of the opinion that there is no justifiable reason to mix html of any kind in with JS.
Yeah.
I said it.

I suggest posting a slightly longer example to make the point, like this one:
$('<li>', {
html: $('<a>', {
href: item.href,
text: item.title
})
});
I agree that you shouldn't mix html and js though, but it may not be worth it to include a template engine into your project if you're adding a small and simple feature to a website.
Useful. I was looking for same thing to display my code in most elegent way. thanks. One more thing. How to add condition or looping in this? like I want to create dynamic <tr> of my table. Or say I want hide/show content.