rain
rain

Reputation: 489

is it possible to set custom attribute by jQuery attr() function using JS variables

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.

Upvotes: 14

Views: 52473

Answers (5)

Sedat Başar
Sedat Başar

Reputation: 3798

I guess you should use this

jQuery('#div').attr(attname,attvalue);

Upvotes: 30

Muhammad Usman
Muhammad Usman

Reputation: 12503

Yes, but use data- prefix before to avoid collision

$('elm').attr('data-'+attname,attvalue);

Using data- prefix doesn't require HTML5.

Upvotes: 16

daryl
daryl

Reputation: 15197

Yes you can add any attribute you want, just be careful:

$('#foobar').attr('foo','bar'); 

http://jsfiddle.net/each/rnnfk/ - Check out this demo

Upvotes: 8

karim79
karim79

Reputation: 342635

Square bracket notation is your friend:

var attname = "haha";
jQuery('#div')[0][attname] = "foo";
alert(jQuery('#div')[0][attname]);

http://jsfiddle.net/KJBHq/

Upvotes: 1

Andy
Andy

Reputation: 30135

<div data-test="lala">asdf</div>

alert($('div').data('test'));
var t = 'data-test2';
var v = 'hiho';
$('div').attr(t,v);
alert($('div').data('test2'));
alert($('div').attr('data-test2'));

this all works for me: http://jsfiddle.net/r7uQ8/ Tested on jquery 1.4.4

Upvotes: 3

Related Questions