Jquery Data vs Attr?
The .data() function stores custom information, outside the DOM. It's ideal for script-only values. .attr() manipulates an element's HTML attributes, modifying how it's presented and behaves.
Use .data() for hidden data and .attr() when changes need to be in the markup. Keep in mind, .data()
is JQuery's own sneaky method, while .attr()
changes are loud and clear in the DOM.
Core concepts unpacked
A closer look at .data()
The .data() is a manipulator of hidden truths, ideal for dealing with complex objects and references. Storing data on a DOM node in jQuery, it's like your app's top secret bunker. It cleverly prevents circular references and memory leaks by storing data in an internal cache rather than directly in the DOM.
With .data()
, you're engaged in:
- Storing non-string values; arrays, objects you name it.
- Retaining information, which doesn't have to take a plane to the server.
- Clasping data that changes often and doesn't affect how your page looks.
Handy, right?
Breaking down .attr()
.attr(), meanwhile, is all cheers and loudspeakers, interacting with HTML attributes as strings, getting down and dirty with the DOM. Perfect for:
- Accessing an attribute's birth value.
- Changes that imprint footprints in the DOM sandbox for serialization.
- State or configuration attributes that change the element's behavior.
Plus, the syntax is as easy as a Sunday morning:
So for your run-of-the-mill attribute values, making changes that reflect in your rendering, or when sending data to the server, .attr() is your trusty sidekick.
Stepping into best practices
Keeping Values Clean
Casing matters! Always use lower case for HTML attribute names when using .attr()
. Also, stick with hyphens for HTML data attributes. A little unpredictability can go a long way when coding.
And, a word of caution! When it comes to numbers, 007
can automatically turn into 7
with .attr()
. So, when using numbers, don’t forget to manually cast your values.
Taking Note of Versions
Starting from jQuery 1.8, there are changes in the way .data()
handles auto-casting. This change can give you surprises, so you might want to run some tests when upgrading:
For Optimal Usage
- Deploy
.data()
when storing complex data or updating plugin configs. - Appoint
.attr()
for data- manipulations*, or when data needs to be serializable. - Treat
.data()
like an intelligence agency, caching and auto-casting data at will. - Use
.attr()
as a public notice, even when jQuery isn't keeping vigil.
Was this article helpful?