Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery assign different values to title element same class

Tags:

html

jquery

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:

  • 0:Mariposa Lily - Calochortus species
  • 1:Mariposa Lily - Calochortus species
  • 2:Mariposa Lily - Calochortus species
  • 3:Radiant Flowers

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?

like image 921
George Sherman Avatar asked Jul 13 '26 22:07

George Sherman


2 Answers

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.

like image 80
Igor Deruga Avatar answered Jul 16 '26 14:07

Igor Deruga


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");
} 
like image 37
Ronen Cypis Avatar answered Jul 16 '26 15:07

Ronen Cypis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!