Last Updated: March 21, 2023
·
145.3K
· david morrow

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:

fatal: refusing to merge unrelated histories

13 Responses
Add your response

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

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

over 1 year ago ·

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 ·

@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 ·

pretty good...

over 1 year ago ·

@dperrymorrow oh ok, now I see!

over 1 year ago ·

just use mootools

over 1 year ago ·

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 ·

This is far more elegant than either of those approaches.

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

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

over 1 year ago ·

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

over 1 year ago ·

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 ·

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 ·

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.

over 1 year ago ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside