HackToHell
HackToHell

Reputation: 2393

Adding a class to img tags using JavaScript

I am a learning javascript guy and I am trying to add the Image Hover Shadow Effect With CSS to my images and for that to work , I have to add an class to all my img tags , which is not possible manually so i am trying to write a javascript that does that and uses jquery , to do so .

it needs to add an class to img tag , such as this

From this

<img border="0"  height="75" src="http://3.bp.blogspot.com/-qhxaAUAJUVQ/TeocW4AuIiI/AAAAAAAABCo/IYy7hQ6-5VQ/s200/CSSEditLogo1.jpg" width="75"/> 

to

<img border="0" class="imagedropshadow" height="75" src="http://3.bp.blogspot.com/-qhxaAUAJUVQ/TeocW4AuIiI/AAAAAAAABCo/IYy7hQ6-5VQ/s200/CSSEditLogo1.jpg" width="75"/>

Can anyone help :)

Thanks

Upvotes: 4

Views: 45650

Answers (5)

Vivek
Vivek

Reputation: 11028

give an ID to your image, let's say it's imgId and then write this jquery (if you want to add class to any specific img tag.)

$(document).ready(function(){ 
      $('#imgId').addClass('imagedropshadow');
});

for all img tag simply use this;

$("img").addClass("imagedropshadow"); 

Upvotes: 2

Xiezi
Xiezi

Reputation: 2989

You can try this:

$('img').addClass('imagedropshadow');

But I suggest you that you add an id or general class into the img tag for selecting.

Upvotes: 1

Jeremy Banks
Jeremy Banks

Reputation: 129746

To add the class to all of the images on your page with jQuery:

$("img").addClass("imagedropshadow")

Without jQuery is is not very difficult either:

var images = document.getElementsByTagName("img");
var i;

for(i = 0; i < images.length; i++) {
    images[i].className += " imagedropshadow";
}

Upvotes: 19

Emil
Emil

Reputation: 8527

Are you sure you need the class. If you are planning to add a css class to all images and hook the shadow to it, you should be able to do it on the img tags directly.

img:hover{
 /*properties*/
}

Upvotes: 2

James Allardice
James Allardice

Reputation: 166061

You can use the addClass function with jQuery. See the API here for examples.

Upvotes: 1

Related Questions