Assigning Data Values to Objects

$("li:eq(0)").data("race","Men"); $("li:eq(1)").data("race","Elves"); $("li:eq(2)").data({race:"Dwarves"}); $("li").each(function(){   $(this).append(" of the race of ");   $(this).append($(this).data("race")); });

jQuery provides the .data(key [,value]) method to store pieces of data as key=value pairs inside the DOM object. This allows you to attach additional pieces of data to the object that you can access later.

There is an alternate form of .data(object) that accepts JavaScript objects containing the key value pairs. This becomes useful when you are already working with objects.

To access a data item once it has been stored, simply call .data(key), which returns the object ...

Get jQuery and JavaScript Phrasebook 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.