How can I apply a function to several images in jQuery?
-
28-09-2019 - |
Pergunta
I need a little help with (probably) something really simple.
I want to use a script which converts images from color to grayscale. I got it working partially — the first image turns gray, but the second won’t.
I know this is because an id cannot be used multiple times:
var imgObj = document.getElementById('grayimage');
I tried this:
var imgObj = $(’.grayimage’)[0];
But it didn’t work. Changing it to getElementByClass
also does not work. (Before people ask, I did change the id
to class in the <img>
tag.)
I really could use some help here. Thanks in advance!
Solução
$('.grayimage').each(function(idx,imgObj){
<do your code here>
});
Outras dicas
$('.grayimage') gives you a list of all elements with grayimage as a class. If you add '[0]' you're accessing the first element, so any changes you make will apply to only the first image that it finds with this class.
You should loop through all elements:
var images = $('.grayimage');
for(i = 0; i < images.length; i++) {
var image = images[i];
// Do stuff
}