jQuery Data - data() Method

Example

Attach data to the element and then retrieve the 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.

Return data from the element

Return data attached to 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 from 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.