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

2

7 Answers 7

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

And addClass for else part.

Comments

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/

Comments

1

This should do it:

$('a img').removeClass().addClass('example')

Comments

1
$(document).ready(function(){
    $('a >img').addClass('sample'); //direct descendant of a
});

Comments

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.