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 which 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)
To remove an attached data use jQuery removeData method.

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

DEMO DOWNLOAD

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 code is given below:

$("#button4").click(function () {
    alert($("#div2").data("name") + "\n" + $("#div2").data("designation") + "\n" + $("#div2").data("languages"));
});

DEMO DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "WordPress, SEO, jQuery, HTML" and more.