Home >Web Front-end >JS Tutorial >jQuery Data Wrangling: When to Use $.data() vs. $.attr()?
Data Wrangling with jQuery: $.data vs $.attr
In the context of manipulating data attributes with jQuery, $.data and $.attr serve distinct purposes.
$.data: Internal Data Storage
$.data is primarily employed for storing data within jQuery's internal cache, $.cache, rather than directly in the DOM. When data is assigned to an element using $.data, it is associated with the element's object, allowing for complex objects and references to be stored. Additionally, $.data performs auto-casting, converting data from strings to recognized types like boolean, number, and JSON.
$.attr: HTML5 Data Attributes
In contrast, $.attr is used to set and retrieve HTML5 data attributes, which are stored as attributes in the DOM. These attributes are designed to facilitate data storage in a standardized manner. When using data attributes, it's crucial to note the hyphen-camelCase conversion that occurs. Hyphens in attribute names are automatically converted to camelCase when accessing data via $.data.
Best Practices
The above is the detailed content of jQuery Data Wrangling: When to Use $.data() vs. $.attr()?. For more information, please follow other related articles on the PHP Chinese website!