How to Remove Data with jQuery removeData
The jQuery .removeData() method allows developers to
manually delete values that were previously attached to DOM elements
using the .data() method. This guide covers how to clear
specific data keys, remove multiple keys at once, and completely wipe
all cached jQuery data from an element, while also highlighting the
distinction between jQuery's internal data cache and HTML5
data-* attributes.
Basic Syntax
The method is called directly on a jQuery element selection:
$(selector).removeData([name]);The name parameter is optional and accepts a string or
an array of strings representing the key(s) you wish to delete.
Removing a Single Data Item
To delete a single stored value, pass the property name as a string
argument to .removeData().
// Setting a data value
$('#userCard').data('role', 'admin');
// Removing the specific data value
$('#userCard').removeData('role');
// Verification: this will now return undefined
console.log($('#userCard').data('role')); Removing Multiple Data Items
You can remove several stored keys at once by providing either a space-separated string or an array of keys.
Using a space-separated string:
$('#userCard').removeData('role status lastLogin');Using an array:
$('#userCard').removeData(['role', 'status', 'lastLogin']);Removing All Stored Data
Calling .removeData() without any arguments removes all
custom data previously assigned to the element via jQuery's internal
cache.
// Store multiple entries
$('#userCard').data({
userId: 101,
tier: 'premium',
active: true
});
// Clear all data stored on this element
$('#userCard').removeData();Important
Difference: HTML5 data-* Attributes
The .removeData() method only affects data stored in
jQuery's internal memory store. It does not remove
physical data-* attributes from the HTML markup.
If the element originated with an HTML attribute like
<div id="userCard" data-role="guest"></div>,
calling $('#userCard').removeData('role') clears the jQuery
cache, but subsequent calls to .data('role') may re-read
the original value from the DOM attribute.
To remove the physical attribute from the DOM completely, use
.removeAttr():
$('#userCard').removeAttr('data-role');