Reputation: 8070
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
Upvotes: 0
Views: 8597
Reputation: 645
$(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.
Upvotes: 2
Reputation: 31
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");
Upvotes: 0
Reputation: 5001
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.
Upvotes: 6
Reputation: 7954
$(document).ready(function(){
$('a >img').addClass('sample'); //direct descendant of a
});
Upvotes: 1
Reputation: 8623
This should do it:
$('a img').removeClass().addClass('example')
Upvotes: 1
Reputation: 1035
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/
Upvotes: 1
Reputation: 11570
if($('a[href=image.png] > img').hasClass('sample')){
$('a[href=image.png] > img').removeClass('sample');
}
And addClass
for else
part.
Upvotes: 1