BlekStena
BlekStena

Reputation: 345

issue adding a class to a dynamically created element

I have some elements that get created on the fly via a plugin I am using, and I want to give a class to a certain div if it is the only div.

If I write conditional that alerts if there is one element, it works (the alert shows up), but if I try to assign a class to it it does not get assigned:

alert code (works)

if ( $('#carousel > div').length == 1 ) {
    alert('code');
}

class code (does NOT work)

if ( $('#carousel > div').length == 1 ) {
    $(this).addClass('code');
}

Upvotes: 1

Views: 552

Answers (3)

Thomas Kekeisen
Thomas Kekeisen

Reputation: 4406

And at all, the if is useless because jQuery can handle "empty" objects. So what you really need is:

$('#carousel > div').addClass('code');

If $('#carousel > div').length is 0, nothing will happen.

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

this is what you think it is. a if block does not change the execution context(this) - this inside the if block will still refer to the same object as it was referring outside the if block, so this inside the if block may not be referring to the div

if ( $('#carousel > div').length == 1 ) {
    $('#carousel > div').addClass('code');
}

Upvotes: 2

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

In your context $(this) does not points the required elements that you want.

Try,

var cache =  $('#carousel > div');
if (cache.length == 1 ) {
    cache.addClass('code');
}

Upvotes: 3

Related Questions