The jQuery data() method can be used to set or return the attached data from the selected element. To find the data attached, you have to first set the data for the related keyname.
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 the selector to select the elements to return or set the data. You have to use tag name, class name, or id of the elements to select. |
keyname | It is the keyword for the data to identify and set the data |
value | It is the value of the data you set. |
Set the Data For the Element
If you want to set the data, you have to specify the value for the keyname you mention. See the example given below to set the data for the selected element.
Example
1 2 3 4 5 6 7 8 9 |
<script> $(document).ready(function(){ $('.mysetbtn').click(function(){ $("div").data("mywebsitename", "Tutorialdeep"); }); }); </script> <button type="button" class="mysetbtn">Click to Set Data</button><br><br> <div></div> |
When you click the button given above, it sets the data ‘Tutorialdeep’ for the keyname ‘mywebsitename’. The div element is given above now contains the set data after you click the button.
Get the Data From the Element Using jQuery data() Method
You can also get or return the data you set for the selected element. First set the data for the selected element with the keyname and its value using jQuery data() Method. After that, get the data you have added by using the example as given below.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<script> $(document).ready(function(){ $('.setbtn').click(function(){ $("div").data("mywebsite", "Tutorialdeep"); }); $('.getbtn').click(function(){ var myvar = $("div").data("mywebsite"); $("div").append(myvar); alert(myvar); }); }); </script> <button type="button" class="setbtn">Click to Set Data</button> <button type="button" class="getbtn">Click to Get Data</button><br><br> <div></div> |
You have to first set the data using the set button given above. After that, click the get button to get the attached data from the selected element.
You may also like to read
I hope you like this tutorial on jQuery data() Method. If you have any queries regarding the tutorial, please comment below.
References