Roberto
Roberto

Reputation: 325

JQuery - add class if element has class

I want to add class to elements which have class 'alignleft'. My code:

$(document).ready(function () {
    if($('.foto').children().hasClass('alignleft')){
        $(this).addClass('animated bounceInLeft');
    }
});

It doesn't work and I don't know why. However if I use $('.foto').children().addClass('animated bounceInLeft'); it applies class to all child elements with class 'alignleft'. So the problem is in $(this) maybe ?

Upvotes: 3

Views: 2636

Answers (3)

zakhefron
zakhefron

Reputation: 1443

Try

$(document).ready(function() {
 var elem = $('.foto .alignleft');
  if (elem) {
    elem.addClass('animated bounceInLeft');
  }
});

or

$(document).ready(function() {
   $('.foto .alignleft').addClass('animated bounceInLeft');
});

$(document).ready(function() {
 var elem = $('.foto .alignleft');
  if (elem) {
    elem.addClass('animated bounceInLeft');
  }
});
.alignleft{color:red;}
.alignright{color:green;}

.animated{background:lightgrey;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foto">
  <div class="alignleft">
    Div A
  </div>
  
  <div class="alignleft">
    Div B
  </div>
  
  <div class="alignright">
    Div C
  </div>
   <div class="alignright">
    Div D
  </div>
</div>

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115242

You can't use this, which refers the window object. Instead use the the class as selector in children() method.

$('.foto').children('.alignleft').addClass('animated bounceInLeft');

Or use child selector(>)

$('.foto > .alignleft').addClass('animated bounceInLeft');

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82241

You can target elements using class selector and then add classes to them:

$('.foto .alignleft').addClass('animated bounceInLeft');

Upvotes: 1

Related Questions