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.

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>

Sign up to request clarification or add additional context in comments.

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>');

Comments

0

You can also used .insertAfter

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

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);

Comments

Your Answer

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.