We are still cooking the magic in the way!
jQuery & DOM Manipulation
Working with Data Attributes
Working with Data Attributes
HTML5 data attributes provide a standardized way to store custom data on elements. jQuery's .data() method makes working with these attributes simple and efficient.
What are Data Attributes?
Data attributes are custom attributes that start with data-. They allow you to embed custom data within HTML elements without using non-standard attributes.
HTML:
<div id="product"
data-id="12345"
data-name="Laptop"
data-price="999.99"
data-in-stock="true"
data-category="electronics">
MacBook Pro
</div>
The .data() Method
The .data() method provides a convenient way to store and retrieve data associated with elements.
Getting Data:
// Get single data attribute
var productId = $("#product").data("id");
console.log(productId); // "12345"
var price = $("#product").data("price");
console.log(price); // "999.99"
// Get all data attributes as object
var allData = $("#product").data();
console.log(allData);
// {id: "12345", name: "Laptop", price: "999.99", inStock: "true", category: "electronics"}
Setting Data:
// Set single data value
$("#product").data("discount", "10%");
// Set multiple data values
$("#product").data({
seller: "TechStore",
warranty: "2 years",
rating: 4.5
});
// Data is stored in jQuery's internal cache
console.log($("#product").data("seller")); // "TechStore"
Important: When you use
.data() to set values, the data is stored in jQuery's internal cache, not as HTML attributes. To set actual HTML data attributes, use .attr("data-name", value).
Data Type Conversion
jQuery automatically converts data attribute values to appropriate JavaScript types.
HTML:
<div id="demo"
data-string="hello"
data-number="42"
data-float="3.14"
data-boolean="true"
data-null="null"
data-json='{"name":"John","age":30}'>
</div>
JavaScript:
var string = $("#demo").data("string");
console.log(typeof string); // "string"
var number = $("#demo").data("number");
console.log(typeof number); // "number"
var float = $("#demo").data("float");
console.log(typeof float); // "number"
var boolean = $("#demo").data("boolean");
console.log(typeof boolean); // "boolean"
var nullValue = $("#demo").data("null");
console.log(nullValue); // null
var json = $("#demo").data("json");
console.log(typeof json); // "object"
console.log(json.name); // "John"
Naming Convention
Data attribute names in HTML use kebab-case, but jQuery converts them to camelCase when accessing via .data().
HTML:
<div id="user"
data-first-name="John"
data-last-name="Doe"
data-user-id="123">
</div>
JavaScript:
// Access using camelCase
var firstName = $("#user").data("firstName"); // "John"
var lastName = $("#user").data("lastName"); // "Doe"
var userId = $("#user").data("userId"); // "123"
// Set using camelCase
$("#user").data("fullName", "John Doe");
// This creates data-full-name in jQuery's cache
The .removeData() Method
Use .removeData() to remove data stored by jQuery.
JavaScript:
// Remove single data item
$("#product").removeData("discount");
// Remove multiple data items
$("#product").removeData("seller warranty");
// Remove all data
$("#product").removeData();
Warning:
.removeData() only removes data from jQuery's internal cache. It does not remove the HTML data-* attributes. Use .removeAttr() to remove HTML attributes.
Practical Example: Product Cards with Details
HTML:
<div class="products">
<div class="product-card"
data-id="1"
data-name="Wireless Mouse"
data-price="29.99"
data-image="mouse.jpg"
data-stock="15">
<h3>Wireless Mouse</h3>
<button class="view-details">View Details</button>
<button class="add-to-cart">Add to Cart</button>
</div>
<div class="product-card"
data-id="2"
data-name="Mechanical Keyboard"
data-price="79.99"
data-image="keyboard.jpg"
data-stock="8">
<h3>Mechanical Keyboard</h3>
<button class="view-details">View Details</button>
<button class="add-to-cart">Add to Cart</button>
</div>
</div>
<div id="product-modal" style="display: none;">
<h2 id="modal-name"></h2>
<img id="modal-image" src="" alt="">
<p>Price: $<span id="modal-price"></span></p>
<p>In Stock: <span id="modal-stock"></span></p>
<button id="close-modal">Close</button>
</div>
JavaScript:
$(document).ready(function() {
// View product details
$(".view-details").click(function() {
var card = $(this).closest(".product-card");
var productData = card.data();
$("#modal-name").text(productData.name);
$("#modal-price").text(productData.price);
$("#modal-stock").text(productData.stock);
$("#modal-image").attr({
src: "images/" + productData.image,
alt: productData.name
});
$("#product-modal").show();
});
// Add to cart
$(".add-to-cart").click(function() {
var card = $(this).closest(".product-card");
var productData = card.data();
// Store cart item data
var cartItem = {
id: productData.id,
name: productData.name,
price: productData.price,
quantity: 1
};
// Add visual feedback
card.data("in-cart", true);
$(this).text("Added!").prop("disabled", true);
console.log("Added to cart:", cartItem);
// Re-enable after 2 seconds
setTimeout(function() {
$(this).text("Add to Cart").prop("disabled", false);
}.bind(this), 2000);
});
// Close modal
$("#close-modal").click(function() {
$("#product-modal").hide();
});
});
Practical Example: Tabs with Dynamic Content
HTML:
<div class="tab-container">
<button class="tab-btn active" data-tab="home" data-icon="🏠">Home</button>
<button class="tab-btn" data-tab="about" data-icon="ℹ️">About</button>
<button class="tab-btn" data-tab="services" data-icon="⚙️">Services</button>
<button class="tab-btn" data-tab="contact" data-icon="📧">Contact</button>
</div>
<div id="tab-content">
<div class="tab-panel active" id="home">Home Content</div>
<div class="tab-panel" id="about">About Content</div>
<div class="tab-panel" id="services">Services Content</div>
<div class="tab-panel" id="contact">Contact Content</div>
</div>
JavaScript:
$(document).ready(function() {
$(".tab-btn").click(function() {
var tabId = $(this).data("tab");
var tabIcon = $(this).data("icon");
// Remove active class from all tabs and panels
$(".tab-btn").removeClass("active");
$(".tab-panel").removeClass("active");
// Add active class to clicked tab and corresponding panel
$(this).addClass("active");
$("#" + tabId).addClass("active");
// Store current tab in data
$(".tab-container").data("currentTab", tabId);
// Log analytics
console.log("Tab viewed:", tabId, tabIcon);
// Store view count
var viewCount = $(this).data("viewCount") || 0;
$(this).data("viewCount", viewCount + 1);
console.log("This tab viewed " + (viewCount + 1) + " times");
});
// Initialize with home tab
$(".tab-container").data("currentTab", "home");
});
Using Data Attributes for Configuration
HTML:
<div class="slider"
data-autoplay="true"
data-interval="3000"
data-loop="true"
data-animation="fade">
<!-- Slider content -->
</div>
JavaScript:
$(document).ready(function() {
$(".slider").each(function() {
var config = $(this).data();
console.log("Slider Config:", config);
// {autoplay: true, interval: 3000, loop: true, animation: "fade"}
if (config.autoplay) {
// Start autoplay with specified interval
setInterval(function() {
// Slide logic here
}, config.interval);
}
// Apply animation style
$(this).attr("data-animation-style", config.animation);
});
});
Exercise:
- Create a user list where each user card has data attributes for: id, name, email, role, and status
- Add a "View Profile" button that displays the user data in a modal
- Add filter buttons (All, Active, Inactive) that show/hide users based on their status data attribute
- Add a "Toggle Status" button that changes the user's status data and updates the display
- Keep track of how many times each user profile has been viewed using jQuery's data storage
Summary
.data(key)- Get data attribute value.data()- Get all data attributes as object.data(key, value)- Set data value (stored in jQuery cache).removeData(key)- Remove data from jQuery cache- Data attributes use kebab-case in HTML, camelCase in JavaScript
- jQuery automatically converts data types (strings, numbers, booleans, objects)
- Use data attributes for storing metadata and configuration
.data()stores in cache;.attr()modifies HTML