Home > Web Front-end > JS Tutorial > jQuery $.attr() vs. $.data(): When to Use Which?

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

Barbara Streisand
Release: 2024-12-20 11:40:10
Original
937 people have browsed it

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

jQuery Data vs Attr

When working with data attributes, there are two primary jQuery methods you can use: $.data and $.attr. Understanding their differences is crucial for effective data storage and retrieval.

$.attr for HTML5 Data-Attributes

If you're dealing with HTML5 data-attributes, such as <a>, the appropriate method is $.attr. This enables you to read and write data-attributes directly from the element's HTML. For instance:

$('#foo').attr('data-foo'); // Outputs: "bar"
$('#foo').attr('data-foo', 'baz'); // Updates the attribute to "baz"
Copy after login

$.data for Arbitrary Data Storage

In contrast, $.data allows you to store arbitrary data on an element, unrelated to specific attributes. This data is not accessible via HTML, but rather through the jQuery cache. It's often used for widget instantiation and storing complex objects. For example:

$('#foo').data('myData', {key: 'value'});
$('#foo').data('myData').key; // Outputs: "value"
Copy after login

Hyphens and CamelCase in $.data

When using $.data, hyphenated data attribute names are automatically converted to camelCase, while the original hyphenated format remains available in HTML. However, using hyphens in JavaScript is not recommended for access via $.data().

Auto-Casting in $.data

Another useful feature of $.data() is its ability to auto-cast values. If the value matches a recognized pattern, it will be converted to the appropriate data type. This simplified pattern:

<a>
Copy after login

Can be accessed as:

$('#foo').data('num'); // Outputs: 15
$('#foo').data('bool'); // Outputs: true
$('#foo').data('json'); // Outputs: {fizz: ['buzz']}
Copy after login

When to Use $.attr vs $.data

Generally, use $.attr for accessing HTML5 data-attributes that require direct interaction with HTML. Use $.data for storing arbitrary data not accessible through HTML, especially when working with complex objects.

The above is the detailed content of jQuery $.attr() vs. $.data(): When to Use Which?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template