Core_Dumped
Core_Dumped

Reputation: 4699

How to append HTML elements in Javascript?

I am trying to append two HTML elements and pass it to the after() function in jquery:

$('div.masterButtons').after(function () {
    var foobar = $('<div>foo<div>bar</div></div>');
    var foobaz = $('<div>foo<div>baz</div></div>');
    return (foobar + foobaz)
    }
);

It prints:

[object Object][object Object]

How do I append the two elements? I am avoiding concatenating two html strings because the divs are far more complicated than these and I would need jquery elements to build it.

Upvotes: 0

Views: 80

Answers (4)

Antoine Chwalek
Antoine Chwalek

Reputation: 45

Based on the jQuery .after() documentation you have many ways to do that.

$('div.masterButtons')
.after('<div>foo<div>bar</div></div>','<div>foo<div>baz</div></div>');

or

$('div.masterButtons')
.after('<div>foo<div>bar</div></div>')
.after('<div>foo<div>baz</div></div>');

or

var barAndBaz = ['<div>foo<div>bar</div></div>','<div>foo<div>baz</div></div>'];
$('div.masterButtons').after(barAndBaz);

Upvotes: 0

zriel
zriel

Reputation: 79

You can also used .insertAfter

$('div.masterButtons').insertAfter('<div>foo<div>bar</div></div>')

Upvotes: 0

hon2a
hon2a

Reputation: 7214

If you really like having the function there, use the answer provided by https://stackoverflow.com/users/114251/arun-p-johny . Alternatively, you could just simplify to:

$('div.masterButtons')
    .after('<div>foo<div>bar</div></div>')
    .after('<div>foo<div>baz</div></div>');

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

both foobar and foobaz are jQuery object, you can't use + to add them

$('div.masterButtons').after(function () {
    var foobar = $('<div>foo<div>bar</div></div>');
    var foobaz = $('<div>foo<div>baz</div></div>');
    return foobar.add(foobaz)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="masterButtons"></div>

Upvotes: 1

Related Questions