How to Set & Get Data on an Element in jQuery

In this tutorial, we will learn how to set and get data on particular HTML elements using the jQuery .data() function.

 

Set Data to an Element

We attach data to an element by passing the jQuery .data() function after an element selector. Pass the key of the data as the first argument of .data() and the value as the second.

 

To demonstrate this, let's create an HTML button element with an id attribute. When a user clicks it, we will store the value true on the button with a key called clicked.

 

<button id="button" type="button">Click to add</button>
$('#button').click(function() {

  $("#button").data("clicked", true);

  console.log($("#button").data("clicked"));

});
true

 

How to Set Arrays and Dictionaries to an Element

A powerful aspect of the jQuery .data() function is not only can it store boolean and string data but more complex data such as arrays and dictionaries:

 

$('#button').click(function() {

$("#button").data("info", {
  'color': 'blue',
  'clicked': true,
  'id': 1
});

console.log($("#button").data("info"));

});
{'color': 'blue', 'clicked': true, 'id': 1}

 

And another example using an array:

 

$('#button').click(function() {

  let items = [1,2,3];

  $("#button").data("info", items);

  console.log($("#button").data("info"));

});
[1,2,3]

 

Get Data Attribute Value

To get data stored on an element, pass the .data() function after an element selector and pass the key of the data to access as the first argument of the function.

 

$('#button').click(function() {

  // set the data:

  $("#button").data("info", {
    'color': 'blue',
    'clicked': true,
    'id': 1
  });

  // get data from button by key name:

  let button_data = $("#button").data("info");


  console.log(button_data);

});
{'color': 'blue', 'clicked': true, 'id': 1}

 

Access Data Attribute in a Dictionary

To access a property on a dictionary stored on an element, pass the key of the property after the .data() function like this:

 

$('#button').click(function() {

// set the data:

$("#button").data("info", {
 'color': 'blue',
 'clicked': true,
 'id': 1
});

// get data from button by key name:

let is_clicked = $("#button").data("info").clicked;


console.log(is_clicked);

});
true

 

Evaluate Data Attribute Value Stored with .data()

To evaluate any data stored on an element, use an evaluation operator after the .data() function like this:

 

if ($("#button").data("clicked") == true) {
  // the value is true, do something here.
}