Reputation: 116273
I have an <a>
element. I then have an associated jQuery object $("a")
which I would like to modify. So I try the following:
$("a").myAttribute = 10;
alert($("a").myAttribute); // <--- Alerts undefined
What is the problem?
Upvotes: 1
Views: 60
Reputation: 76880
you could do:
$("a").attr('myattribute', '10');//store the attribute
In any case you should traget it a little better because with $("a") you ar targeting all links in the page so a better thing to do is:
$("a#myid").attr('myattribute', '10');
if you just need to save data related to the object you should use data()
$("a#myid").data('myattribute', '10');
//to retrieve it use
var my = $("a#myid").data('myattribute')
//you can still use 'a' for example a.hide() hides all links
EDIT - if you need to attach an object you should consider doing this:
var a = $('a');
//use the reference from now on
a.secondObject = SecondjQueryObject
Upvotes: 3
Reputation: 245419
Each use of $('a') returns a different instance of an object. While your original code won't work, you should be able to do:
var a = $('a');
a.myAttribute = 10;
alert(a.myAttribute.toString());
If you actually want to add the value to the DOM so that you can use it later, the "correct" way would be to use either the attr method (if you're setting a valid HTML attribute) or the data method (if you want to use a non-standard name):
// valid HTML attribute
$('a').attr('name', 'someName');
// non-standard name
$('a').data('myAttribute', 10);
And then later:
alert($('a').attr('name'));
Or:
alert($('a').data('myAttribute'));
If you need something more complex (like storing a complex object rather than a simple attribute/data value), I would consider writing a simple jQuery Plugin which extends the jQuery object and ads the storage/retrieval methods required for your custom object.
To get started with a simple example, check out jQuery's plugin authoring page:
Upvotes: 4
Reputation: 78650
@nicola is right that you should use attr
. However, to clarify the reason that came back undefined. In the code:
$("a").myAttribute = 10;
alert($("a").myAttribute);
The first $("a")
and the 2nd $("a")
are two separate objects. Each time you call $
you are creating a new object. These objects in this case happen to hold the same set of elements, but they are still two distinct objects. You are then modifying the first object and checking to see if the modification exists on the 2nd. Obviously it doesn't. The following will actually do what you were expecting:
var a = $("a");
a.myAttribute = 10;
alert(a.myAttribute);
But this will only modify that specific javascript object and not the element(s) which the objects contain. This is why you want to use attr
. This will actually add the attribute to the underlying elements.
I would suggest looking into data
though, as I find it a better approach then creating arbitrary attributes. http://api.jquery.com/jQuery.data/
Upvotes: 0