jQuery Data – Method to Attach and Get unlimited data from selected elements

jQuery Data – Method to Attach and Get unlimited data from selected elements

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.

Syntax 1 of jQuery Data Method

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)

jQuery Data Example: Attach Data to Div & Get Data back from Div

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"));
});

Syntax 2 of jQuery Data Method

Attaching a data object.

$(selector).data(object)

When getting the attached data.

$(selector).data(name)

jQuery Data Example: Using data Object to Attach Data to Div & Get Data back

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:

DOWNLOAD

SHARE THIS ARTICLE

  • linkedin
  • reddit
yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate