Ricardo
Ricardo

Reputation: 35

How to change with jQuery a data attribute of a set of elements?

say I have a set of elements $elements. Say they all have a data attr named "amount". First one has data-amount = 1, second 2 and so on. Whats the simplest way to increment in x that value for all of them. y solution is

$elements.each(function(){
    $(this).data('amount',$(this).data('amount')+=x);
});

Is there a better solution, without using the each statement? Thanks!

Upvotes: 2

Views: 216

Answers (2)

David Tang
David Tang

Reputation: 93694

jQuery, as of v1.6.2 at least, doesn't offer an overload for .data() that accepts a function. Still using each, but within it you can do:

$(this).data().amount += x;

Upvotes: 3

Tomalak
Tomalak

Reputation: 338406

$elements.data('amount', function () {
    return $(this).data('amount') += x;
});

Upvotes: 1

Related Questions