tags:

views:

205

answers:

6

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 with that is that myClass gets added to $(this) rather than the newly created DIV.

So I gave this a try:

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

But jQuery doesn't like that either.

I can do this, however:

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

jQuery is OK with that syntax. Of course, I lose the ability to pass it in as a variable.

I'm guessing I'm doing something fairly obviously wrong. But I'm stumped as to what that is.

+3  A: 

maybe something like:

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

using the & didnt work because this is not vb, string concatenation is done with the +

John Boker
"because this is not vb". DOH! (I'm slapping my forehead right now). Clearly I did not get enough sleep last night.
DA
it could happen to anyone :)
John Boker
+5  A: 
$(this).after( $("<div></div>").addClass(myClass) );
Kobi
I have no idea why it never occurred to me but I never thought to nest statements in jQuery. Thanks, Kobi!
DA
+2  A: 

I usually end up doing something like this:

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

Did you try using a "+" character instead of a "&" ? And by the way, I don't see any semicolon at the end of some commands, might that be wrong ?

var myClass = "thisIsMyClass";
$(this).after("<div class='"+ thisIsMyClass +"'></div>");
Daan
+2  A: 
$("<div></div>").insertAfter(this).addClass(myClass);
Kristopher Johnson
That's an interesting option. Thanks!
DA
+2  A: 

The JQuery after method returns the same selector that you called after on to allow for method chaining (as do most JQuery methods), which is why your class name is going on to the this element.

To do this you can either do:

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

or reverse the selector order :

$('<div></div>').insertAfter($(this)).addClass('thisIsMyClass');
jjacka