I'm using jquery 1.5 and html4 standard.
I'm trying to set custom attribute which i get by javascript variable, but it is not setting up.code sample:
var attname="list1"; // this is changed on every call of the function where it is defined.
var attvalue="b,c,d"; // this also changed.
jQuery('#div1').attr({attname:attvalue});
but it treat attname as string itself rather variable. there are other option like using data(),prop() but they are supported in HTML5 and jquery 1.6 that is not possible for me at the moment.other problem is data can't be set on server side to be sync and used at client side by jquery data(). as they are syntactically diff. if there's some other way please suggest Thanks.
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. When this method is used to set attribute values, it sets one or more attribute/value pairs for the set of matched elements.
Set Attributes - attr() The jQuery attr() method is also used to set/change attribute values.
The custom attributes allow you to treat elements in particular ways within the JavaScript code for the page, for example when using animated display functions. It's really only advisable to use custom attributes if there is no standard HTML attribute available to do what you need.
Basically, . data() is for setting or checking the jQuery object's data value. If you are checking it and it doesn't already have one, it creates the value based on the data attribute that is in the DOM. . attr() is for setting or checking the DOM element's attribute value and will not touch the jQuery data value.
I guess you should use this
jQuery('#div').attr(attname,attvalue);
Yes, but use data-
prefix before to avoid collision
$('elm').attr('data-'+attname,attvalue);
Using data-
prefix doesn't require HTML5.
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