Reputation: 33
EDITED- to FIX self inflicted errors.
I have a group of images and their URLS. They are all within the same class. I would like to assign a new title to the image based upon their index position. For example images 1-3 should be "Radiant Flowers", 4-6 would be glorious shrubs.
$('.flower').each(function (index, value) {
console.log(index + ':' + $(this).attr('title'));
if (index === 2)) {
$('.flower').attr('title',"Radiant Flowers");
}
});
the console shows the following output:
So when I inspect the elements, the titles are all changed to Radiant Flowers. What I have noticed is that when I can get this to work the code changes all values instead of the ones I had hoped to affect. Is there a way to do this?
Upvotes: 3
Views: 96
Reputation: 1546
Your parseInt takes a bad argument: 'index' > 2 You should change it to parseInt(index) > 2, I think...
About the actual problem: you loop through your elements and you detect the one you want to modify... and then you modify all the elements with the class "flower".
The good way to do it would be to put this inside your "if": $(this).attr('title', "Radiant Flowers");
The reason is that $('.flower') will select ALL the elements with CSS class "flower", but you need to change only the current element. That is why, $(this) should work. Even better, you can use $(value) becase "value" is the variable that points to the current element in the foreach loop.
Upvotes: 2
Reputation: 21470
What happened there, is that this line: $('.flower').attr('title',"Radiant Flowers");
actually change all of the elements with class flower
, and not the ones you wanted to change.
In order to fix this, in you code, change this:
if (index === 2)) {
$('.flower').attr('title',"Radiant Flowers");
}
to
if (index > 2)) {
$(this).attr('title',"Radiant Flowers");
}
Upvotes: 1