Reputation: 4898
I want to assign a custom value to an element. It seems that .attr(customName, value) will work fine for this. If the attribute doesn't exist (it won't) jQuery creates it and lays in the value I provide. Later I'm able to read the value with .attr(customName), as if it were a normal HTML-known attribute. I know there's an HTML5 .data() method for this kind of thing but it's not persistent. If I move the html off to a disk and then retrieve it, anything set with data() will be gone, while .attr() goes right into the HTML.
I don't see in the .attr() documentation where it's guaranteed to create a new attr name if it doesn't recognize what you give it, so I'm a bit nervous. Is it safe to use .attr() this way? Thanks.
Upvotes: 1
Views: 199
Reputation: 10677
Yes, you can do that. It won't be valid HTML, however. What you would be doing is creating a new fork of XHTML. You could create your own DTD to validate against, but that's probably not necessary.
Just keep in mind that you may run into issues with some browsers (especially older versions of IE). However, most browsers will just ignore unknown attributes and you would therefore be free to do with them what you please. Whether or not you care that your HTML is invalid is your call, but for practical purposes it would work fine as long as you avoid certain reserved attribute names (like id
or class
).
You might want to take a step back and re-evaluate what you are trying to accomplish, however, since there are probably better ways of storing persistent data in your document.
Upvotes: 1
Reputation: 337560
You should not use attr()
to create an attribute which is not in the HTML specification as it will render your page invalid, and lead to other problems.
I assume what you mean by .data()
not being persistent is that the values do not appear in the rendered source, as they are kept in a cached object which jQuery holds.
What you instead can do is set your data attributes using attr()
:
$('#foo').attr('data-bar', 'wibble');
Upvotes: 1
Reputation: 10736
You should be using data to create custom attributes. It works cross browser using .data() and you can keep it in your markup so it doesn't get reset. Nettuts Data Attr Article
E.g.
<a href="#" data-custom-description="lorum ipsum">tool tip</a>
$('a').data('custom-description');
-> returns lorum ipsum
Upvotes: 1