frequent
frequent

Reputation: 28523

how to append a variable to an HTML element stored as string using Jquery?

I have an empty controlgroup, which I want to populate with buttons. Can't get it to work.

This is the controlgroup:

var $wrap = '<div class="wrap"><div data-role="controlgroup"></div></div>';

This is the button:

var $btn = '<a href="#some" data-role="button">Click</a>'

I want to do something like this:

$wrap.append( $btn );

But it's not working.

Can someone tell me what I'm doing wrong? I think $wrap is just a string, so I cannot call append on it. If so, how do I do it correctly?

Thanks for help!

Upvotes: 0

Views: 11869

Answers (4)

adeneo
adeneo

Reputation: 318352

var $wrap = $('<div class="wrap"><div data-role="controlgroup"></div></div>');
var $btn = $('<a href="#some" data-role="button">Click</a>');
$wrap.append( $btn );

There's probably fifty ways to this, like:

var $wrap = $('<div class="wrap"><div data-role="controlgroup"></div></div>'),
    $btn = '<a href="#some" data-role="button">Click</a>';

$wrap.children().append( $btn );

or:

var $wrap = $('<div class="wrap"><div data-role="controlgroup"></div></div>'),
    $btn = '<a href="#some" data-role="button">Click</a>';

$('[data-role="controlgroup"]', $wrap).append( $btn );

Upvotes: 2

wong2
wong2

Reputation: 35760

I think $wrap is just a string, so I cannot call append on it.

Yes.

You could try:

var $wrap = $('<div class="wrap"><div data-role="controlgroup"></div></div>');
var $btn = '<a href="#some" data-role="button">Click</a>';
$wrap.append( $btn );

Upvotes: 0

Alex Turpin
Alex Turpin

Reputation: 47776

Well, first off, those are strings. You'll want to turn them into jQuery objects using $.

var $wrap = $('<div class="wrap"><div data-role="controlgroup"></div></div>');
var $btn = $('<a href="#some" data-role="button">Click</a>');

Now to append $btn into $wrap, you can go find the inner div (which is where you want to append the element) and use .append:

$wrap.find("div").append($btn);

Live example

Upvotes: 1

James Montagne
James Montagne

Reputation: 78750

You simply have strings, you need a jquery object to call append:

var $wrap = $('<div class="wrap"><div data-role="controlgroup"></div></div>');

Upvotes: 1

Related Questions