Vonder Vonder - 2 months ago 11
jQuery Question

Displaying variable as a class name in Jquery

I am trying to incrementally display divs using Jquery, but I have a problem with getting the right syntax for displaying the variable as a class. Here is my code:

var mydiv_id = 'wacek_'+$a; /wacek_1, wacek_2, etc

$("<div class="+mydiv_id"></div>").appendTo('body');
$( ".col-sm-4" ).append( $( '.'+mydiv_id ) );
$('.'+mydiv_id).hide();


I cannot get this right, any help would be greately appreciated.

Answer

Please use

$("<div class='"+mydiv_id+"'></div>").appendTo('body');

Instead of

$("<div class="+mydiv_id"></div>").appendTo('body');

Please check below snippet for more understanding.

var $a = '1';
var mydiv_id = 'wacek_'+$a; //wacek_1, wacek_2, etc 

$("<div class='"+mydiv_id+"'></div>").appendTo('body');
$( ".col-sm-4" ).append( $( '.'+mydiv_id ) );
$('.'+mydiv_id).hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>