Banana
Banana

Reputation: 4218

Access $.data() inside a selector

I have the following code:

<img class="sth" data-number="1" src="sth.jpg" alt="">

There are a couple of such elements, and they all differ only in data-number. I want to do the following for all elements:

$('.sth').attr('src', 'sth' + data('number') + '.jpg');

so that every image changes the src with its own number.

However, data('number') does not work, and $('.sth').data('number') changes all with sth1.jpg.

Is there a way to do this?

Upvotes: 1

Views: 62

Answers (2)

wirey00
wirey00

Reputation: 33661

You can do it using attr() function

$('.sth').attr('src', function(){
    return 'sth' + $(this).data('number') + '.jpg';
});

Upvotes: 3

Tom Walters
Tom Walters

Reputation: 15616

Yep, using the jquery each() function like so:

$('.sth').each(function(){
    $(this).attr('src', 'sth' + $(this).data('number') + '.jpg');
});

Which will execute on each element matched by the .sth selector.

Upvotes: 1

Related Questions