jQuery Data - jQuery.data() Method

Example

Attach data to the element and then retrieve that data:

$("#btn1").click(function(){
  $("div").data("greeting", "Hello World");
});
$("#btn2").click(function(){
  alert($("div").data("greeting"));
});

Try it yourself

Definition and Usage

The .data() method attaches data to the selected element or retrieves data from the selected element.

Note:This is a low-level method; use .data() More convenient.

Return data from the element

Return the attached data from the selected element.

Syntax

$(selector).data(name)
Parameter Description
name

Optional. Specifies the name of the data to be retrieved.

If the name is not specified, this method will return all stored data in the element in the form of an object.

Attach data to the element

Attach data to the selected element.

Syntax

$(selector).data(name,value)
Parameter Description
name Required. Specifies the name of the data to be set.
value Required. Specifies the value of the data to be set.

Attach data to the element using an object

Use an object to add data to the selected elements.

Syntax

$(selector).data(object)

Try it yourself

Parameter Description
object Required. Specifies an object containing name/value pairs.