← Back to Index

.data()

Store arbitrary data associated with the matched elements or return the value at the named data store for the first element.

Examples

1. Store data

$('div').data('role', 'admin');

Result

// Data is stored internally.
// $('div').data('role') returns "admin"

2. Store object

$('div').data({ id: 123, active: true });

Result

// $('div').data('id') returns 123
// $('div').data('active') returns true

3. Read from data-* attribute

// <div data-user='{"name":"John"}'></div>
const user = $('div').data('user');

Result

// Returns parsed object
{ name: "John" }

Parameters

Parameter Type Description
name string | object The name of the data key, or an object of key-value pairs to set.
value any The value to store. If undefined, acts as a getter.

Returns: The data value for getter, or the original SR object for setter.