JQuery: append div with class that is a var

MeltingDog picture MeltingDog · Dec 29, 2012 · Viewed 8.5k times · Source

I have a line that appends a new div to an existing one. However I also want to add a class to the new div. The class's name is actually held in a var.

I am just unsure of the syntax of this - could anyone point me in the right direction at all?

 var itemclass = "myclass";

 $('#wrapper').append('<div class="itemclass"></div>');

So far I have tried:

 $('#wrapper').append('<div class=" . itemclass . "></div>');

 $('#wrapper').append('<div class=" & itemclass & "></div>');

To no effect... any help is appreciated!

Answer

janith picture janith · Dec 29, 2012

You are concatenating a string, it is done like:

$('#wrapper').append('<div class="' + itemclass + '"></div>');