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.

8 Answers 8

13
$(this).after( $("<div></div>").addClass(myClass) );
Sign up to request clarification or add additional context in comments.

1 Comment

I have no idea why it never occurred to me but I never thought to nest statements in jQuery. Thanks, Kobi!
5

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 +

1 Comment

"because this is not vb". DOH! (I'm slapping my forehead right now). Clearly I did not get enough sleep last night.
3

I usually end up doing something like this:

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

Comments

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

1 Comment

That's an interesting option. Thanks!
2

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

Comments

0

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

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.