Extend jQuery removeData() to add the following functionality:
- Optionally remove the corresponding data-attribute on the element (if added without using
.data()
) - Only remove the attribute if the value matches one passed in the options
- Allow data attribute value to be passed containing
data-
Current Version: 2.0.0
Include jQuery and jQuery.removeData.js
in your HTML document. Supports jQuery version 1.7+
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="jQuery.removeData.js"></script>
Call the removeData()
method on any element with a data attribute.
HTML
<div data-foo="selector" data-bar="baz" data-boom="bloz">content</div>
jQuery
remove just data cache (original behaviour)
$('div[data-foo=selector]').removeData('bar');
jQuery
removes data cache and attribute
$('div[data-foo=selector]').removeData('bar', {
removeAttr: true
});
jQuery
removes data cache (and optionally attribute) if value matches
$('div[data-foo=selector]').removeData('bar', {
values: 'baz'
});
$('div[data-foo=selector]').removeData('bar', {
removeAttr: true,
values: 'baz'
});
Variations
The attribute value can cater for the following variations
$('div[data-foo=selector]').removeData('bar');
$('div[data-foo=selector]').removeData('data-bar');
$('div[data-foo=selector]').removeData('[bar, boom]');
$('div[data-foo=selector]').removeData('[data-bar, data-boom]');
$('div[data-foo=selector]').removeData('bar boom');
$('div[data-foo=selector]').removeData('data-bar data-boom');
The values option can cater for the following variations
$('div[data-foo=selector]').removeData('bar', {values: 'baz'});
$('div[data-foo=selector]').removeData('[bar, boom]', {values: ['baz','bloz']});
$('div[data-foo=selector]').removeData('bar boom', {values: 'baz bloz'});
This will remove both the bar and boom attributes
$('div[data-foo=selector]').removeData(['bar','boom'], {values:'baz'});
But this will remove just the bar attribute
$('div[data-foo=selector]').removeData(['bar','boom'], {values:['baz','']});
These will also remove both the bar and boom attributes
$('div[data-foo=selector]').removeData(['bar','boom'], {values:[undefined, 'baz']});
$('div[data-foo=selector]').removeData(['bar','boom'], {values:['baz', null]});
This will remove just the bar attribute
note the space after baz. this will translate to ['baz','']
$('div[data-foo=selector]').removeData(['bar','boom'], {values:'baz '});
For more edge cases, see the test suite
Run the unit tests with a local server that supports PHP. Ensure that you run the tests from the test directory. No database is required. Pre-configured php local servers are available for Windows and Mac. Here are some options:
- Windows: WAMP download
- Mac: MAMP download
- Linux: Setting up LAMP
- Mongoose (most platforms)
Ensure you select the Enable coverage option to see test coverage provided by Blanket.js.
If you discover any issues or have questions regarding usage, please add an issue on GitHub.