Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append DIV and immediately add class in jQuery

Tags:

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 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.

like image 995
DA. Avatar asked Jan 05 '10 18:01

DA.


2 Answers

$(this).after( $("<div></div>").addClass(myClass) );
like image 121
Kobi Avatar answered Nov 15 '22 08:11

Kobi


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 +

like image 38
John Boker Avatar answered Nov 15 '22 07:11

John Boker