0

How can i add the class selectors dynamically to the img tag. For Example: img tag should be inside the anchor tag then only the class name:sample should add dynamically whichever anchor tag contain img like, Before:

<a href="image.png"><img src="image.png"/></a>

After:

<a href="image.png"><img src="image.png" class="sample"/></a>

If already image tag contain class then remove that class and the new class is possible in jquery. I am not sure, how can i do this in jQuery. Any suggestion would be great.

Thanks, vicky

Vignesh Pichamani
  • 7,950
  • 22
  • 77
  • 115
  • 1
    Just use: [`.addClass()`](http://api.jquery.com/addClass/), [`.hasClass()`](http://api.jquery.com/hasClass/) and [`.removeClass()`](http://api.jquery.com/removeClass/). Or use [`.not()`](http://api.jquery.com/not/) instead of `.hasClass()`. – Joe Jul 08 '13 at 11:17
  • see this http://stackoverflow.com/questions/5995628/adding-attribute-in-jquery to remove attribute add removeAttr() before the attr() – L10 Jul 08 '13 at 11:19

7 Answers7

6

You just need to toggle your class. To do this, see:

$("img").toggleClass("border");

I made an example for you on CodePen. Just click here.

Guilherme Oderdenge
  • 4,935
  • 6
  • 61
  • 96
2
$(document).ready(function(){
$('your selector').addClass('sample'); //It can be select,img,a,etc.. });

Be specific in your tag for choosing. I use in CakePHP 3.x Date HtmlHelper field and it worked like a magic.

1
if($('a[href=image.png] > img').hasClass('sample')){
    $('a[href=image.png] > img').removeClass('sample');
}

And addClass for else part.

Paritosh
  • 11,144
  • 5
  • 56
  • 74
1

This can be done easily via jQuery.addClass and jQuery.removeClass APIs..

Add Class - http://api.jquery.com/addClass/ Remove Class - http://api.jquery.com/removeClass/

abipc
  • 997
  • 2
  • 13
  • 35
1

This should do it:

$('a img').removeClass().addClass('example')
Hieu Nguyen
  • 8,563
  • 2
  • 36
  • 43
1
$(document).ready(function(){
    $('a >img').addClass('sample'); //direct descendant of a
});
coolguy
  • 7,866
  • 9
  • 45
  • 71
0

HTML code:

<img id="testImg" src="xyz.jpg" />

css code:

.displayNone{ display:none; }

jquery - to add class

`$("#testImg").addClass("displayNone");`

jquery - to remove class

$("#testImg").removeClass("displayNone");

user2502452
  • 31
  • 1
  • 2