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?
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, ...})
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With