The jQuery Data Method – .data() is used to attach unlimited data on selected elements. It is also used to retrieve data that are attached on elements.
When attaching a data.
$(selector).data(name,value)
Parameter | Description |
---|---|
name | name of the data |
value | value of the data name |
When getting the attached data.
$(selector).data(name)
There is a div element where I will attach a data.
There are 2 buttons, one will attach data and the other will get this attached data. Finally the data is shown on the alert box.
<div id="div1"></div>
<button id="button1">Attach Data to Div</button> <button id="button2">Get Data from Div</button>
The button clicks of these 2 buttons are given below:
$("#button1").click(function () {
$("#div1").data("name", "Yogi");
});
$("#button2").click(function () {
alert($("#div1").data("name"));
});
Attaching a data object.
$(selector).data(object)
When getting the attached data.
$(selector).data(name)
Here I have similar setup – 1 div and 2 buttons.
<div id="div2"></div>
<button id="button3">Attach Data to Div</button>
<button id="button4">Get Data from Div</button>
I will attach data using object. Therefore first I store 3 data on an object. These are – ‘name’, ‘designation’ & ‘languages’.
myObj = new Object();
myObj.name = "Yogi";
myObj.designation = "Programmer";
myObj.languages = "JavaScript, jQuery, C#";
Then on the first button click I will attach this object on the div element.
$("#button3").click(function () {
$("#div2").data(myObj);
});
Finally on the second button click I will get this data and show it on the alert box.
The 2nd button click event code is given below:
$("#button4").click(function () {
alert($("#div2").data("name") + "\n" + $("#div2").data("designation") + "\n" + $("#div2").data("languages"));
});
Refer the DOWNLOAD link: