evmqoa
Last Updated: April 12, 2018
·
95.02K
· dperrymorrow

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.

14 Responses
Add your response

3425

Um, doesn't this simply work? Why create a jquery object?

$('body').html('<div class="spinner"></div>')

over 1 year ago ·
3427

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

over 1 year ago ·
3429

I've always been doing my jQuery DOM element creation this way, mostly because it allows you to attach event handlers to element right in there.

As a side note though, if you're doing lots of complicated DOM element creation, it could be better to go with client-side templates. This is a decent introduction to doing that using underscore.js: Using Underscore.js Templates To Render HTML Partials

over 1 year ago ·
3430

@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}));
over 1 year ago ·
3435

pretty good...

over 1 year ago ·
3440

@dperrymorrow oh ok, now I see!

over 1 year ago ·
6756

just use mootools

over 1 year ago ·
6761

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.

over 1 year ago ·
6773

This is far more elegant than either of those approaches.

document.body.grab(new Element('div').addClass('spinner'));
over 1 year ago ·
12178

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

over 1 year ago ·
12179

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

over 1 year ago ·
13585

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.

over 1 year ago ·
14032

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.

over 1 year ago ·
29813

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.

8 months ago ·