Is it possible to set multiple data attributes using the jQuery.attr() function?

This works:

$(myObj).attr("data-test-1", num1);
$(myObj).attr("data-test-2", num2);

But this doesn't:

$(myObj).attr({
  data-test-1: num1,
  data-test-2: num2
});

Am I missing something really obvious here?


Sure, like this:

$(myObj).attr({"data-test-1": num1, "data-test-2": num2});

Like the .attr() docs state:

Setting several attributes at once

To change the alt attribute and add the title attribute at the same time, pass both sets of names and values into the method at once using a plain JavaScript object. Each key-value pair in the object adds or modifies an attribute:

$('#greatphoto').attr({
  alt: 'Beijing Brush Seller',
  title: 'photo by Kelly Clark'
});

When setting multiple attributes, the quotes around attribute names are optional.


Yes it is possible to setup multiple attributes, just use simple Object literal syntax. Example:

$('#my_image').attr({
  alt: 'Beijing Brush Seller',
  title: 'photo by Kelly Clark'
});

More info about attr method can be found here.


Sorry for posting an answer to an already solved question after so many years.

I just thought about keeping the thread up to date with recommended solution[citation needed] as on date.

Since jQuery 1.2.3, there is a .data() function that takes arguments to get/set data attributes (setting multiple was available since 1.4.3) like this:

/* 
 ** 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 must be noted that setting data attributes with .data() doesn't update the DOM, so you can't see these in the DOM inspector. Also, they are not cross compatible with .attr(). However, the data attributes set with .attr() can be retrieved with .data() (in short, any attributes that begin with 'data-' can be retrieved with .data()).

// Setter
$('#my_image').attr('data-test-3', 'num3');    // note the 'data-' on attr name

// Getter
$('#my_image').data('test-3');    // num3