Q:

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

A:

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

A:

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

