HTML and CSS Reference
In-Depth Information
Example: The jQuery data() method
The jQuery library has provided support for accessing and manipulating custom data
since version 1.4.3. This support was updated in jQuery 1.6 to conform to changes in
the HTML5 specification; use this version of jQuery if possible (see http://www.web ).
Using the jQuery data() method is straightforward. Let's return to an earlier example
to see how it works:
<li data-year="1996" data-color="white" data-engine="VR6">Cabrio</li>
alert($("li").data("year")); // alerts "1996"
alert($("li").data("engine")); // alerts "VR6"
// let's repaint the car again
$("li").data("color", "yellow");
// and add the rating data
$("li").data("rating", "awesome");
The jQuery data() method successfully reads the data-year and data-engine attributes
defined in the markup, but if you access data-color via the dataset API or examine the
DOM object, you neither see its value turn yellow nor find a data-rating attribute, as
you did in Recipe 6.5 :
alert($("li").data("color")); // alerts "yellow"
alert(document.getElementsByTagName("li")[0].dataset.color); // alerts "white"
While jQuery reads in the data from the custom data attributes, it does not write this
data back to the DOM; instead, it stores the data in a JavaScript object. This speeds up
applications where a lot of data access or manipulation is performed. However, if you
forget this difference and try to also use the dataset API in your application, you will
encounter some unexpected results.
See Also
A small sampling of applications utilizing microdata:
• PaintbrushJS by Dave Shea:
• Dynamic Google Analytics Tagging by Jason Karns:
• SXSW 2010 Parties site by Christopher Schmitt, Kyle Simpson, Stephanie Sullivan,
and Zoe Gillenwater:
Search WWH ::

Custom Search