"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > The timing of using $.data() and $.attr() in jQuery

The timing of using $.data() and $.attr() in jQuery

Posted on 2025-04-16
Browse:560

jQuery $.data() vs. $.attr(): When to Use Which?

jQuery Data vs Attr: Understanding the Differences

In jQuery, both $.data and $.attr are used to manipulate attributes in DOM elements. However, they serve distinct purposes and differ in their usage and behavior.

When to Use $.data

$.data is primarily used to store data associated with a DOM element within jQuery's internal cache ($.cache). This data is not stored as HTML attributes on the element itself. Hence, if you need to store data persistently for data-binding or custom scripting purposes, $.data is the preferred choice.

Example:

$('#foo').data('myData', 'someValue');
// Gets the stored data
$('#foo').data('myData'); // outputs "someValue"

When to Use $.attr

$.attr, on the other hand, primarily sets or retrieves HTML5 data-attributes. These data-attributes are stored as attributes on the DOM element and are intended to provide additional metadata or content.

Example:

$('#foo').attr('data-attribute'); // outputs "myCoolValue"
$('#foo').attr('data-attribute', 'newValue'); // Sets the data-attribute to "newValue"

Additional Considerations

  • Data storage with $.data supports complex objects, whereas HTML data-attributes can only contain strings.
  • $.data auto-casts values into their appropriate types when retrieving data, such as converting "true" to a boolean.
  • $.attr preserves the original data type when retrieving data.
  • To avoid confusion, it is recommended to use camelCase syntax when accessing data stored with $.data.
  • You can also use $.removeAttr to remove data-attributes, which does not have a direct equivalent with $.data.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3