Abhik
Abhik

Reputation: 674

Add Class To Element If it already has a specific class

I am trying to dynamically add a class to slide-content and slide-buttons within the Bootstrap Carousel's caption div. I want my code to add the class animate only when the the parent div with the class item has the class active added to it. (the classactive is added only when the item slides in in.). Here is the basic HTML of the Carousel.

  <div class="carousel-inner" role="listbox">
  <!-- Item 1 -->
    <div class="item active">
      <img src="..." alt="...">
      <div class="carousel-caption">
        <div class="slide-content>
        ...
        </div>
        <div class="slider-buttons">
        ...
        </div>
      </div>
    </div>
    <!-- /Item 1 -->
    <!-- Item 2 -->
    <div class="item">
      <img src="..." alt="...">
      <div class="carousel-caption">
        <div class="slide-content>
        ...
        </div>
        <div class="slider-buttons">
        ...
        </div>
      </div>
    </div>
    <!-- /Item 2 -->
    ...
  </div>

And, here is what I tried.

$item = $('.carousel-inner > .item');
$( $('.carousel-inner > .item') ).each(function() {
if ( this.hasClass('active') ) {
    $('.carousel-caption > .slide-content, .carousel-caption > .slider-buttons').addClass('animated');
} else {
    $('.carousel-caption > .slide-content, .carousel-caption > .slider-buttons').removeClass('animated');
}
});

Now, when I remove the jQuery's each function, it adds the class animated to all the elements when any of the item gets the class active. Also, it doesn't remove the class at all (since the the classactive is there, inspite of the parent div.). And, when I add the each function, it doesn't work at all.

Please help.

Upvotes: 0

Views: 797

Answers (2)

SCO
SCO

Reputation: 1932

My guess :

  $('.carousel-inner :not(.active)').find('.slide-content,.slider-buttons').removeClass('animated');
  $('.carousel-inner .active').find('.slide-content,.slider-buttons').addClass('animated');

Btw, you forgot the closing double-quote in :

<div class="slide-content>

It should read this instead :

<div class="slide-content">

Upvotes: 0

Satpal
Satpal

Reputation: 133403

You can traverse the elements using proper selector

var inner = $('.carousel-inner');

//traverse not active item then find the buttons and remove the animated class
inner.find('> .item:not(.active) .carousel-caption').children('.slide-content .slider-buttons').removeClass('animated');

//traverse active item then find the buttons and add the animated class
inner.find('> .item.active .carousel-caption').children('.slide-content .slider-buttons').addClass('animated');

Upvotes: 1

Related Questions