14

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.

1
  • karim79 Thanks for edit @Sedat thanks to point the syntax error i was making. Brogrammer ,Usman, Andy Thanks all for providing input every one was correct in one or other way. Commented Sep 21, 2011 at 9:38

5 Answers 5

30

I guess you should use this

jQuery('#div').attr(attname,attvalue);
Sign up to request clarification or add additional context in comments.

Comments

16

Yes, but use data- prefix before to avoid collision

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

Using data- prefix doesn't require HTML5.

Comments

8

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

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

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

Comments

3
<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

2 Comments

Pretty sure if you read his question he doesn't want the use of data attributes.
@Brogrammer: Hm I understood it that way, that he meant he can't use data because he thought they only work in jquery 1.6. So i pointed out that they do work in 1.4.4 as well. And using them would be more elegant in my opinion.
1

Square bracket notation is your friend:

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

http://jsfiddle.net/KJBHq/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.