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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Each use of $(‘a’) returns a different instance of an object. While your original code won’t work, you should be able to do:
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):
And then later:
Or:
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:
Plugins/Authoring – jQuery