Keywords: jQuery | Data Attributes | DOM Manipulation | HTML5 | Frontend Development
Abstract: This article provides a comprehensive examination of the core distinctions between jQuery's data() and attr() methods when handling DOM data attributes. Through practical code examples, it reveals how the data() method stores data in jQuery's internal object rather than actual DOM attributes, while contrasting with the attr() method's direct manipulation of HTML attributes. The paper further explores standard usage of HTML5 data-* attributes, JavaScript dataset property access, and application scenarios of data attributes in CSS, offering front-end developers complete solutions for data attribute management.
Core Differences in jQuery Data Storage Mechanisms
In jQuery development, data attribute handling involves two fundamentally different approaches: .data() and .attr(). While these methods appear functionally similar on the surface, their underlying implementation mechanisms and application scenarios exhibit significant differences.
Working Principle of the data() Method
When using $('div').data('info', 1), jQuery does not create an actual data-info attribute on the DOM element. Instead, the data is stored in jQuery's internal data cache object. This design offers performance advantages by avoiding frequent DOM operations, but simultaneously creates issues where selectors cannot directly match via attribute selectors.
// Data stored in jQuery internal cache, not visible in DOM
$('div').data('info', 1);
alert($('div').data('info')); // Output: 1
// The following selector cannot match because no data-info attribute exists in DOM
$('div[data-info="1"]').text('222'); // Does not work
Direct DOM Manipulation with attr() Method
In contrast, the .attr() method directly creates or modifies HTML attributes on DOM elements. Using $('div').attr('data-info', '222') creates a genuine data-info attribute on the element, enabling proper matching by CSS selectors and attribute selectors.
// Create actual data-info attribute in DOM
$('div').attr('data-info', '222');
// Selector now works correctly
$('div[data-info="222"]').html('Content updated');
HTML5 Data Attribute Standard Specification
HTML5 introduced the data-* attribute specification, allowing developers to store custom data on standard HTML elements. These attributes, prefixed with data-, provide standardized data storage mechanisms for web applications.
<article
id="electric-cars"
data-columns="3"
data-index-number="12314"
data-parent="cars">
<!-- Electric car content -->
</article>
Dataset Property Access in JavaScript
Modern browsers provide the dataset property to simplify data attribute access. This property returns a DOMStringMap object, allowing direct reading and writing of data attribute values.
const article = document.querySelector("#electric-cars");
console.log(article.dataset.columns); // "3"
console.log(article.dataset.indexNumber); // "12314"
console.log(article.dataset.parent); // "cars"
// Modify data attribute value
article.dataset.columns = "5"; // Changes data-columns attribute value to "5"
Data Attribute Applications in CSS
Data attributes hold significant value in CSS as well. Through attribute selectors and the attr() function, state-based style control can be implemented.
/* Set different widths based on data column count */
article[data-columns="3"] {
width: 400px;
}
article[data-columns="4"] {
width: 600px;
}
/* Display data content using attr() function */
article::before {
content: attr(data-parent);
}
Practical Application Scenario Comparison
In component development, data attribute selection should be based on specific requirements. For internal data requiring frequent read/write operations without CSS selector matching, the .data() method offers better performance. For data needed in styling layers or selectors, the .attr() method is more appropriate.
// Scenario 1: Internal state management (recommend data())
$('.component').data('isActive', true);
if ($('.component').data('isActive')) {
// Execute active state logic
}
// Scenario 2: Style control (must use attr())
$('.component').attr('data-state', 'active');
// CSS can apply styles based on data-state attribute
.component[data-state="active"] {
background-color: #e8f5e8;
}
Performance and Compatibility Considerations
The .data() method, by avoiding DOM operations, provides superior performance in scenarios involving frequent data updates. The .attr() method, while triggering DOM repaints, offers better cross-framework compatibility. In projects with high compatibility requirements, we recommend prioritizing standard data-* attributes combined with the dataset API.
Best Practice Recommendations
Based on the above analysis, we recommend: use the .data() method for temporary, frequently changing internal state data; use the .attr() method to create standard data-* attributes for persistent data needed in styling, selectors, or cross-script usage. This layered strategy ensures performance while maintaining code maintainability and standardization.