Skip to content Skip to sidebar Skip to footer

Appending A Class To The First Div Of A Set Of Dynamically Created Divs

I run in to a situation where I need to append a class called 'active' in to a set of dynamically created divs. My issue is that I am suppose to only add the class 'active' to the

Solution 1:

After appending your div, you can use .first() to get the first div with class item and bgwhite, then add class active to it using .addClass():

Reduce the set of matched elements to the first in the set.

$('.item.bgwhite').first().addClass('active');

Solution 2:

Without the use of jquery, using css just add this selector with your style rules:

.carousel-inner div:first-of-type {background:red;}

Solution 3:

$("#CAROUSEL_CONTENTHERE > div:first-child").addClass("active");

Solution 4:

You can use JQuery Append to append any HTML you want.. and then use :first selector to select by the first matched element, then use addClass to add the active class to that element.. See this fiddle:

http://jsfiddle.net/jFIT/s4swZ/

var dynamicDiv = '<div class="item bgwhite"><div class="carousel-img-full"><a href="#"><img src="img/banner2.jpg" alt=""></a></div></div>';

$('#CAROUSEL_CONTENTHERE').append(dynamicDiv);
$('#CAROUSEL_CONTENTHERE').append(dynamicDiv);
$('#CAROUSEL_CONTENTHERE').append(dynamicDiv);

if(!$('#CAROUSEL_CONTENTHERE DIV.item.bgwhite:first').hasClass('active'))
{
    $('#CAROUSEL_CONTENTHERE DIV.item.bgwhite:first').addClass('active');
}

Solution 5:

You may try this (Example, for example active has background:red):

$('.item.bgwhite:first').addClass('active');

You may use :first to select the first item matched with classes.

Post a Comment for "Appending A Class To The First Div Of A Set Of Dynamically Created Divs"