jQuery.data(): underappreciated

by hyun
May 28, 2010

One of the most underappreciated jQuery methods has to be .data(). It allows you to associate arbitrary named values with DOM elements. Usage is simple:

 

$("body").data("x", 1);
$("body").data("y", someObject);

 

You can store any data types and expect the same back.

 

As a web developer, I’m sure some of you have assigned arbitrary values to DOM nodes for any one of a multitude of reasons, like this:

<div class="foo1" customattribute="xyz">
<div class="foo2" customattribute="abc">

$(".foo1").attr("customattribute");
$(".foo2").attr("customattribute");

 

With .data(), you no longer have to embed oddly named attributes just to store a value to a DOM node. You can replace the above with:

 

$(".foo1").data("customattribute", "xyz");
$(".foo2").data("customattribute", "abc");
$(".foo1").data("customattribute");
$(".foo2").data("customattribute");

 

The end result is the same, but the latter gives you cleaner, valid markup.