The data method
The data method allows you to bind any type of data to DOM elements in a safe way, which avoids memory leaks. We can set several different values for an element and retrieve them later. Using the data method to update data does not affect the attributes in the DOM.
Syntax
This is how we set a value for some element and a key by which it can be found later:
.data(key, value);
We can also pass an object that contains key-value pairs to update the data:
.data(object);
You can get the data associated with the first element in a jQuery collection by passing just the key:
.data(key);
Without passing any parameters, we can read the data previously associated with DOM elements. The method will return a JavaScript object containing each value as a property:
.data();
Example
Let's use data to set the data for the tag p, passing 'test' as the first parameter and 21 as the second. Then read the data stored with the key 'test':
<p>text</p>
$('p').data('test', 21); // here the data is written console.log($('p').data('test')); // will output the number 21 console.log($('p').data()); // will output the object {test: 21}
See also
-
method
removeData,
which removes data from an element -
method
hasData,
which checks if an element contains data -
method
attr,
which allows you to get and change any attribute of an element -
JavaScript property
dataset,
which allows you to add your own attributes to tags