john smith
john smith

Reputation: 561

Creating more than one dynamic div with jquery

I am using the following code to dynamically create divs inside new divs:

var obj = {
  name: 'item'
};

obj.html = jQuery('<div/>', { class: 'recommended' });
obj.html += jQuery('<div/>', { class: 'bestbuy' });

jQuery('<div/>', obj).appendTo('#wrapper');

So, basically it should create something like this:

<div id="wrapper">
  <div name='item'>
    <div class="I_will_be_inside_obj"></div>
    <div class="I_will_also_be_inside_obj"></div>
  </div>
</div>

The problem is that this only works with ONE appended div, when I try appending the second, all I get is this:

<div id="wrapper">
  <div name='item'>
    [object Object][object Object]
  </div>
</div>

Any ideas why, and how to fix this? Thanks in advance.

Upvotes: 2

Views: 275

Answers (2)

MattW
MattW

Reputation: 4628

What jQuery returns is an array-like object. You can't use += on it like that.

For this particular example, you can use .after(), but be aware that if the jQuery you're calling .after() on contains multiple elements, it will append a clone of the argument after every element.

var underConstruction;

underConstruction = jQuery('<div/>', { class: 'I_will_be_inside_obj' });
underConstruction.after(jQuery('<div/>', { class: 'I_will_also_be_inside_obj' }));

jQuery('<div/>').append(underConstruction).appendTo('#wrapper');

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382092

That's because the created dom fragment must be an element. You may do this :

jQuery('<div/>').addClass('I_will_be_inside_obj').appendTo('#wrapper');
jQuery('<div/>').addClass('I_will_also_be_inside_obj').appendTo('#wrapper');

or

var obj = { };
obj.html = jQuery('<div/>').addClass('I_will_be_inside_obj');
obj.html += jQuery('<div/>').addClass('I_will_also_be_inside_obj');
jQuery('#wrapper').html(obj.html);

If what you want is to make one div wrapping the 2 divs, use this :

var obj = { };
var div = $('<div/>').appendTo('#wrapper');
jQuery('<div/>').addClass('I_will_be_inside_obj').appendTo(div);
jQuery('<div/>').addClass('I_will_also_be_inside_obj').appendTo(div);

Upvotes: 3

Related Questions