jQuery data() method
The data() method is used to attach and get data from the selected elements. It is an inbuilt method in JQuery. We can use the removeData() method to remove the data.
The commonly used syntaxes of this method are given as follows. Below there are two syntaxes in which the first syntax is used to return data from a selected element, and the second syntax is used to attach data to selected elements.
The name in the above syntax is an optional parameter. It is the data name to retrieve the data. If it is not specified, the data() method returns all stored data for the element as an object. This syntax returns the retrieved data for the selected element.
This syntax is used to attach data to selected elements. The parameters name and value in the above syntax are the mandatory parameters. The name specifies the data name to set, and the value specifies the data value to set.
Now, let’s see an example of using the data() method to understand how to return and attach the data to selected elements.
In this example, we are attaching the data to the div element. Here, there are two buttons named as Attach data and Get data. The Attach data button attaches the data to the div element, and on clicking the Get data button, the data of div element will be retrieved.
If we click the Get data button before clicking the Attach data button, we will get undefined. So, to see the attached data, we have to click the Get data button after clicking the Attach data button.
After the execution of the above code, the output will be –
On clicking the Attach data button, the output will be –
Now, on clicking the Get data button, the output will be –