The jQuery removeData() method can be used to remove all or specified previously set data. The data is previously set with the jQuery Data() method.
Syntax
The syntax of this method is given below:-
Description of the Parameters
The description of the parameters is given below.
Parameter Name | Description |
---|---|
selector | Specify to select the element and remove the set data. You can use tag name, class name, or id of the elements to select. |
keyname | It is the name of data to identify with its set value. |
value | It is the value specified for the data. |
jQuery removeData() Method to Remove All Attached Data
If you want to remove all the attached data from the selected element, you have to use the below example. The example first sets the two data using the data() method. After that, it removes all the data using the jQuery removeData() method without specifying any parameter.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<script> $(document).ready(function(){ $('.setallbtn').click(function(){ $("div").data("SQL", "Query Language"); $("div").data("PHP", "Scripting Language"); var varsqldata = $("div").data("SQL"); var varphpdata = $("div").data("PHP"); alert("One data is: "+varsqldata+", Second data is: "+varphpdata); }); $('.removeallbtn').click(function(){ $("div").removeData(); alert("One data is: "+$("div").data("SQL")+", Second data is: "+$("div").data("PHP")); }); }); </script> <button type="button" class="setallbtn">Click to Set Two Data</button> <button type="button" class="removeallbtn">Click to Remove All Data</button><br><br> <div></div> |
Output
You have to click the set button given above to set the data. It sets two data which you can check in the alert box. Now, click the remove button to remove all the data attached to the selected element.
Remove Specified Attached Data Using Method
You can also remove only the specified data using the jQuery removeData() method. Specify the data contains the keyname and its value. After that, remove the specified data by specifying the parameter withing the removeData() method.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<script> $(document).ready(function(){ $('.setbtn').click(function(){ $("div").data("mywebsite", "Welcome to Tutorialdeep!"); var myvar = $("div").data("mywebsite"); alert(myvar); }); $('.removebtn').click(function(){ $("div").removeData("mywebsite"); alert($("div").data("mywebsite")); }); }); </script> <button type="button" class="setbtn">Click to Set Data</button> <button type="button" class="removebtn btn btn-primary">Click to Remove Data</button><br><br> <div></div> |
Output
When you click the set button, it first set the data for the selected element. After that, click the remove button to remove the specified keyname data.
You may also like to read
I hope you like this tutorial on jQuery removeData() Method. If you have any queries regarding the tutorial, please comment below.
References