Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 356
Garry Pettet Avatar asked May 07 '13 15:05

Garry Pettet


People also ask

How do I set multiple attributes in jQuery?

The attr() method in jQuery is used to set or return the attributes and values of the selected elements. To set multiple attributes and values: $(selector). attr({attribute:value, attribute:value, ...})

What is the use of attr () method in jQuery?

jQuery attr() Method The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element.

Can you have multiple data attributes?

A data attribute is a custom attribute that stores information. Data attributes always start with “data-” then followed with a descriptive name of the data that is being stored. You can have multiple data attributes on an element and be used on any HTML element.


2 Answers

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.

like image 167
j08691 Avatar answered Sep 30 '22 14:09

j08691


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.

like image 37
Goran Avatar answered Sep 30 '22 15:09

Goran