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

It works:

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

But this is not so:

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

Did I miss something really obvious here?

+58
javascript jquery
May 7, '13 at 15:17
source share
3 answers

Of course, like this:

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

Like .attr() , docs:

Setting multiple attributes at once

To change the alt attribute and add the title attribute at the same time, pass both sets of names and values ​​to the method simultaneously using a simple JavaScript object. Each pair of key values ​​in an object adds or modifies an attribute:

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

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

+121
May 7, '13 at 15:19
source share

Yes, it is possible to set multiple attributes, just use the simple object literal syntax. Example:

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

More information on the attr method can be found here .

+4
May 7, '13 at 15:19
source share

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 
0
Jun 11 '19 at 5:34
source share



All Articles