0

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.

asked Nov 21, 2014 at 8:43
1
  • Tried using Handelbars or other templating framework? Commented Nov 21, 2014 at 8:46

4 Answers 4

1

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>

answered Nov 21, 2014 at 8:43

Comments

1

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>');
answered Nov 21, 2014 at 8:48

Comments

0

You can also used .insertAfter

$('div.masterButtons').insertAfter('<div>foo<div>bar</div></div>')
Stéphane Bruckert
23.1k14 gold badges102 silver badges136 bronze badges
answered Nov 21, 2014 at 9:52

Comments

0

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);
answered Nov 21, 2014 at 10:36

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.