Getting and Setting Element Data

jQuery defines a getter/setter method named data() that sets or queries data associated with any document element or with the Document or Window object. The ability to associate data with any element is important and powerful: it is the basis for jQuery’s event handler registration, effecting queuing mechanisms. You may sometimes want to use the data() method in your own code.

To associate data with the elements in a jQuery object, call data() as a setter method, passing a name and a value as the two arguments. Alternatively, you can pass a single object to the data() setter and each property of that object will be used as a name/value pair to associate with the element or elements of the jQuery object. Note, however, that when you pass an object to data(), the properties of that object replace any data previously associated with the element. Unlike many of the other setter methods we’ve seen, data() does not invoke functions you pass. If you pass a function as the second argument to data(), that function is stored, just as any other value would be.

The data() method can also serve as a getter, of course. When invoked with no arguments, it returns an object containing all name/value pairs associated with the first element in the jQuery object. When you invoke data() with a single string argument, it returns the value associated with that string for the first element.

Use the removeData() method to remove data from an element. (Using data() to set ...

Get jQuery Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.