Sorry for posting an answer to an already resolved question after so many years.
I was just thinking about keeping the thread up to date with the recommended solution [quote needed] as on a date.
Starting with jQuery 1.2.3 , there is a function .data() which takes arguments for getting / setting data attributes (setting the plural has been available since 1.4.3 ), for example:
/* ** In all the example below, note that ** 'data-' is removed from attribute name */ // Setter (single) $('#my_image').data('test-1', 'num1'); $('#my_image').data('test-2', 'num2'); // Setter (multiple) $('#my_image').data({'test-1':'num1', 'test-2':'num2'}); // Getter (single) $('#my_image').data('test-1'); // num1 $('#my_image').data('test-2'); // num2
It should be noted that setting data attributes using .data() does not update the DOM, so they cannot be seen in the DOM inspector. In addition, they are incompatible with .attr() . However, data attributes set using .attr() can be obtained using .data() (in short, any attributes starting with 'data-' can be obtained using .data() ).
// Setter $('#my_image').attr('data-test-3', 'num3'); // note the 'data-' on attr name // Getter $('#my_image').data('test-3'); // num3
Fr0zenFyr Jun 11 '19 at 5:34 am 2019-06-11 05:34
source share