Data Attributes
HTML5 gives us the ability to use custom data attributes on elements:
<div data-foo="bar"></div>For working with data attributes, jQuery has several methods:
get all values as key-value pairs:
{ key: value }
get a value by key
set a value
set multiple values
remove a value by key or keys
remove multiple values
<div id="my" data-foo="bar"></div>$("#my").data("foo"); // >>> bar
$("#my").attr("data-foo"); // >>> bar
$("#my").data("foo", "xyz");
$("#my").data("foo"); // >>> xyz
$("#my").attr("data-foo"); // >>> bar !!!
$("#my").attr("data-foo", "def");
$("#my").data("foo"); // >>> xyz !!!
$("#my").attr("data-foo"); // >>> defAn interactive example:
Last updated