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
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