DA.
DA.

Reputation: 40673

Append DIV and immediately add class in 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.

Upvotes: 6

Views: 18642

Answers (8)

Ashish Kwatra
Ashish Kwatra

Reputation: 129

Although Replying it very late but it's a concrete solution to the above ques.You can add a div with a class to any selector through js like this:

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

Upvotes: 0

PrimeLens
PrimeLens

Reputation: 2707

I've been doing this because its super easy to read when I visit code later

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

Upvotes: 0

jjacka
jjacka

Reputation: 531

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');

Upvotes: 2

Kristopher Johnson
Kristopher Johnson

Reputation: 82535

$("<div></div>").insertAfter(this).addClass(myClass);

Upvotes: 2

Daan
Daan

Reputation: 1879

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>");

Upvotes: 0

gnarf
gnarf

Reputation: 106332

I usually end up doing something like this:

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

Upvotes: 3

Kobi
Kobi

Reputation: 138007

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

Upvotes: 13

John Boker
John Boker

Reputation: 83699

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 +

Upvotes: 5

Related Questions