O'Reilly logo

jQuery and JavaScript Phrasebook by Brad Dayley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required