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 div
s are far more complicated than these and I would need jquery elements to build it.
-
Tried using Handelbars or other templating framework?Beri– Beri2014年11月21日 08:46:05 +00:00Commented Nov 21, 2014 at 8:46
4 Answers 4
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>
Comments
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
You can also used .insertAfter
$('div.masterButtons').insertAfter('<div>foo<div>bar</div></div>')
Comments
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);