jQuery data() Method

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.

jQuery data() Method

Syntax

The syntax of this method is given below:-

Get the attached data of an element
$(selector).data(keyname)
Set data of an element
$(selector).data(keyname, value)

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

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

Test it Live

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