Add a DIV and immediately add a class to jQuery

What I'm trying to accomplish: I want to add a DIV after an existing DIV and assign it a specific class.

I started with this:

var myClass = "thisIsMyClass"; $(this).after("<div></div>").addClass(myClass) 

The problem is that myClass is added to $ (this), and not to the newly created DIV.

So I tried:

 var myClass = "thisIsMyClass"; $(this).after("<div class='" & thisIsMyClass & "'></div>") 

But jQuery doesn't like it either.

I can do this, however:

 $(this).after("<div class='thisIsMyClass'></div>") 

jQuery is fine with this syntax. Of course, I lose the ability to pass it as a variable.

I suppose I'm doing something quite obviously wrong. But I'm at a standstill what it is.

+6
jquery
source share
8 answers
 $(this).after( $("<div></div>").addClass(myClass) ); 
+13
source share

maybe something like:

 var myClass = "thisIsMyClass"; var div = $("<div></div>").addClass(myClass); $(this).after(div); 

using the and didnt command because it is not vb, string concatenation is done with

+5
source share

Usually I do something like this:

 var myClass = 'thisIsMyClass'; $(this).after($("<div/>").addClass(myClass)); 
+3
source share
 $("<div></div>").insertAfter(this).addClass(myClass); 
+2
source share

The jQuery after method returns the same selector that you called after inclusion to provide a chain of methods (like most jQuery methods), so your class name goes to that element.

To do this, you can:

 $(this).after($('<div class="' + myClass + '"></div>')); 

or cancel the selection order:

 $('<div></div>').insertAfter($(this)).addClass('thisIsMyClass'); 
+2
source share

Have you tried using the + symbol instead of " & "? And by the way, I don’t see a semicolon at the end of some commands, maybe this is wrong?

 var myClass = "thisIsMyClass"; $(this).after("<div class='"+ thisIsMyClass +"'></div>"); 
0
source share

I do this because its super easy to read when I visit the code later

 $('#description').append('<p></p>'); $('#description p:last-child').addClass('name'); 
0
source share

Although the answer to it is very late, but this is a specific solution to the above questions. You can add a div with a class to any selector via js as follows:

 $('<div/>',{ class : 'sample'}).appendTo("body"); 
0
source share

All Articles