jQuery API

.data()

Contents:

.data( key, value ) Returns: jQuery

Description: Store arbitrary data associated with the matched elements.

  • version added: 1.2.3.data( key, value )

    keyA string naming the piece of data to set.

    valueThe new data value; it can be any Javascript type including Array or Object.

  • version added: 1.4.3.data( obj )

    objAn object of key-value pairs of data to update.

The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks.

We can set several distinct values for a single element and retrieve them later:

$('body').data('foo', 52);
$('body').data('bar', { myType: 'test', count: 40 });

$('body').data('foo'); // 52
$('body').data(); // {foo: 52, bar: { myType: 'test', count: 40 }}

In jQuery 1.4.3 setting an element's data object with .data(obj) extends the data previously stored with that element. jQuery itself uses the .data() method to save information under the names 'events' and 'handle', and also reserves any data name starting with an underscore ('_') for internal use.

Prior to jQuery 1.4.3 (starting in jQuery 1.4) the .data() method completely replaced all data, instead of just extending the data object. If you are using third-party plugins it may not be advisable to completely replace the element's data object, since plugins may have also set data.

Due to the way browsers interact with plugins and external code, the .data() method cannot be used on <object> (unless it's a Flash plugin), <applet> or <embed> elements.

Additional Notes:

  • Note that this method currently does not provide cross-platform support for setting data on XML documents, as Internet Explorer does not allow data to be attached via expando properties.

Example:

Store then retrieve a value from the div element.

<!DOCTYPE html>
<html>
<head>
  <style>
  div { color:blue; }
  span { color:red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <div>
    The values stored were 
    <span></span>
    and
    <span></span>
  </div>
<script>
$("div").data("test", { first: 16, last: "pizza!" });
$("span:first").text($("div").data("test").first);
$("span:last").text($("div").data("test").last);
</script>

</body>
</html>

Demo:

.data( key ) Returns: Object

Description: Returns value at named data store for the first element in the jQuery collection, as set by data(name, value).

  • version added: 1.2.3.data( key )

    keyName of the data stored.

  • version added: 1.4.data()

The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks. We can retrieve several distinct values for a single element one at a time, or as a set:

alert($('body').data('foo'));
alert($('body').data());

The above lines alert the data values that were set on the body element. If no data at all was set on that element, undefined is returned.

alert( $("body").data("foo")); //undefined
$("body").data("bar", "foobar");
alert( $("body").data("bar")); //foobar

HTML 5 data- Attributes

As of jQuery 1.4.3 HTML 5 data- attributes will be automatically pulled in to jQuery's data object. The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification.

For example, given the following HTML:

<div data-role="page" data-last-value="43" data-hidden="true" data-options='{"name":"John"}'></div>

All of the following jQuery code will work.

$("div").data("role") === "page";
$("div").data("lastValue") === 43;
$("div").data("hidden") === true;
$("div").data("options").name === "John";

Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null) otherwise it is left as a string. To retrieve the value's attribute as a string without any attempt to convert it, use the attr() method. When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names. The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).

Calling .data() with no parameters retrieves all of the values as a JavaScript object. This object can be safely cached in a variable as long as a new object is not set with .data(obj). Using the object directly to get or set values is faster than making individual calls to .data() to get or set each value:

var mydata = $("#mydiv").data();
if ( mydata.count < 9 ) {
    mydata.count = 43;
    mydata.status = "embiggened";
}

Additional Notes:

  • Note that this method currently does not provide cross-platform support for setting data on XML documents, as Internet Explorer does not allow data to be attached via expando properties.

Example:

Get the data named "blah" stored at for an element.

<!DOCTYPE html>
<html>
<head>
  <style>
  div { margin:5px; background:yellow; }
  button { margin:5px; font-size:14px; }
  p { margin:5px; color:blue; }
  span { color:red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <div>A div</div>
  <button>Get "blah" from the div</button>
  <button>Set "blah" to "hello"</button>

  <button>Set "blah" to 86</button>
  <button>Remove "blah" from the div</button>
  <p>The "blah" value of this div is <span>?</span></p>
<script>
$("button").click(function(e) {
  var value;

  switch ($("button").index(this)) {
    case 0 :
      value = $("div").data("blah");
      break;
    case 1 :
      $("div").data("blah", "hello");
      value = "Stored!";
      break;
    case 2 :
      $("div").data("blah", 86);
      value = "Stored!";
      break;
    case 3 :
      $("div").removeData("blah");
      value = "Removed!";
      break;
  }

  $("span").text("" + value);
});

</script>

</body>
</html>

Demo:

Support and Contributions

Need help with .data() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to .data()? Report it to the jQuery core team.

Found a problem with this documentation? Report it to the jQuery API team.

* All fields are required
  • Bob

    I’ve found that you can cache the data “object” and have its contents persist through other parts of the code. What I mean is that if you have one function in your javascript modifying your data like so:

    var data = $(‘#dataElement’).data(‘data’);
    data.param = ‘value’;
    data.arg = ‘argument’;

    Then the contents of data will be the same immediately after doing this through caching. If you have another function in your javascript that executes later and does this:

    var param = $(‘#dataElement’).data(‘data’).param;

    You are guaranteed that param == ‘value’ will be true. However, what I’m wondering is that if you cache data and modify the cached variable, instead of calling .data(), will this improve performance?

    If it does improve performance, caching .data() would be important in places in your code where you call .data() often.

  • http://ejohn.org/ John Resig

    This is a safe practice (caching the object returned from .data()) and definitely something we recommend for performance. That is a big reason why we exposed the API in 1.4!

  • Anonymous

    I would like to know all the reserved keys used by jQuery internally, like “events”, so that I will not accidentally overwrite them.
    By the way wouldn’t it be better if we cannot overwrite them, or at least having them prefixed with something like underscores (eg. “__events”), so that we do not have to be aware of them?

  • Anonymous

    I used $.data(this) to get the unique id of an element. With 1.4 is not possible, what can i use instead?

  • Loïc

    I make the same use of $.data(), most of the time for other js libraries working only with dom elements identified by their #id while my dom elements don’t have any since they are generated on the fly.
    Maybe there is another way to do the job if the “unique id way” is not the right one, any suggestion ?
    Thanks a lot for 1.4 !
    Loïc

  • Sebastian B.

    I agree to helianthus.

    But special data properties like .events should IMO rather be hidden from data() methods. Or are there use cases where .events needs to be read/written?

    If yes .events (and any other special properties, if there are any) should be documented here (along with some use cases) to make them part of the official, stable API.

  • question

    The following moment is very interesting. Can anybody comment it?

    // Alert doesn’t work
    $(‘click me’).click( function(){alert(‘where?’)} ).data( {key: ‘val’} ).appendTo( ‘body’ );
    //Alert
    $(‘click me!’).click( function(){alert(‘there!’)} ).data(‘key’,'val’).appendTo( ‘body’ );

    Why is it happened?

  • http://twitter.com/jasonatennui Jason Lengstorf

    That’s definitely strange behavior. If you swap the order of the method calls, it works as expected:

    $(‘click me’)
    .data( {key: ‘val’} )
    .bind(“click”, function(){alert(‘where: ‘+$(this).data(“key”))} )
    .appendTo( ‘body’ );

    But adding data after binding causes the alert to fail:

    $(‘click me’)
    .bind(“click”, function(){alert(‘where: ‘+$(this).data(“key”))} ) // doesn’t work
    .data( {key: ‘val’} )
    .appendTo( ‘body’ );

  • question

    Ok, I’ve understand the cause of it:

    If we set an element’s data using an object, all data previously stored with that element is overridden. Because this data includes events that have been bound to the element, we should use caution when setting .data() with an object.

  • http://profiles.yahoo.com/u/4RMMGEPRK6DNTP2NAAUBA4X4GU Peter

    I noticed that modifying event handlers through this object works. However, the handlers are in an array and it doesn’t seem super smart to mess with them this way. Still trying to figure out how it helps to have events on this object.

  • http://twitter.com/rayie Raymond Ie

    to get the id attribute’s value of an element you can also use $(..).attr(‘id’), or if ‘this’ is already the element $(this).attr(‘id’).

    But then if your elements don’t have an id attribute, then do you mean you just want to get the el the DOM elements themselves, which the selectors give you , or use $(..).get( n ) where n is the posiiton in the set of elements.

  • dude

    You could also just use this.id…

  • http://twitter.com/rayie Raymond Ie

    Just to clarify, this.id would only work if ‘this’ refers to the native DOM element. .id won’t work off a jquery wrapped element.

  • http://www.google.com/profiles/arturadib Artur

    It’d be nice if one could do something like:

    $(“#test”).data(“variable”)++;

  • Mike

    I think you mean $(this).attr(‘id’);

  • Bob

    You could do something like that. For example, you could initialize your data like so:

    $(“#test”).data(“variable”, {variable: 0});

    Then, you could do something like this:

    $(“#test”).data(“variable”).variable++;

    That will work as expected. Of course, now you have to access that value using:

    $(“#test”).data(“variable”).variable;

    Instead of just using .data(“variable”), but depending on what is more convenient to you it might not be a problem.

  • http://twitter.com/jethrolarson Jethro Larson

    Good observation. To help prevent this problem you can extend the data object.

    $(“a”).each(function(){
    $(this).data($.extend($(this).data(),{myprop:true}));
    });

    That way you’re not replacing the existing data, just adding to it.

  • Zachary

    Here’s my problem. Let’s say I have the following code:

    United States
    Great Britain

    and some data on the page in a hidden div:

    { “US”:”US”, “GB”:”GB” }

    and the following javascript:

    var currentValSelected = jQuery(“#countryList”).val(),
    countryJSON = jQuery(“#availableCountries”).data(“countryMap”, JSON.parse(jQuery(“#availableCountries”)[0].firstChild.nodeValue.trim());

    If I do: alert(jQuery(“#availableCountries”).data(“countryMap”).GB), the code works. But if I replace GB with a variable like: alert(jQuery(“#availableCountries”).data(“countryMap).currentValSelected), the code fails. Returns an undefined value.

    How can I work around this?

  • Zachary

    By the way, I’m not looking for support. I’m just wondering why it fails and what the workaround in this case would be.

  • james

    alert(jQuery(“#availableCountries”).data(“countryMap)[currentValSelected])

  • Charlie

    I’m curious–where is this data stored on the element? I’d like to know just in case I have to debug something, and need to see the data object using something like Firebug.

  • Bob

    Actually, there’s this good extension to Firebug, called FireQuery. With FireQuery and Firebug, you will be able to see the data stored on a given element using jQuery.

  • Anonymous

    When you access an Object key via dot notation, javascript only lets you use a string, it won’t evaluate a variable. James’s example accesses the property via Array notation, and js will evaluate a variable value.

    var myObj={“foo”:”bar”}
    var whichProp=”foo”;

    //all output Bar
    alert(myObj.foo);
    alert(myObj[whichProp]);
    alert(myObj["foo"]);

    //undefined
    alert(myObj.whichProp);

  • http://acatalept.com/blog acatalept

    It’s not obvious from the documentation, but it appears you can store a function (or a reference to a function) using a .data() call:

    // store anonymous function in .data()
    $(‘#el’).data(‘myFunc’, function(text){ alert(text); });
    // alert the string “Hello!”
    $(‘#el’).data(‘myFunc’)(‘Hello!’);

    Are there any drawbacks to doing this?

    I’m no javascript expert, and I’m still not real clear on where jQuery is keeping this data, and how well it cleans up after itself. My concern is primarily if I’m creating and destroying a number of DOM elements on the fly, and attaching functions for use with these temporary elements, will there be any performance issues versus, say, referencing a more permanent function:

    // define permanent function
    window.namedFunc = function(text){ alert(text); };
    // reference permanent function within .data()
    $(‘#el’).data(‘myFunc’, namedFunc);
    // alert the string “Hello!”
    $(‘#el’).data(‘myFunc’)(‘Hello!’);

  • Bob

    The data function is very good for caching of elements you know you will access later using jQuery. If you store your data on one hidden element with a very simple selector (for example, $(‘#myData’).data(‘data’)), then the speed gains you will get if you’re using a complicated selector will be very significant.

    Instead of using the full selector to access a given element every time, you will use that selector only once, store it to the data element (for example, $(‘#myData’).data(‘myElement’, $(‘very-complicated-selector’))), and from then on, if you need to access the element, just do $(‘#myData’).data(‘myElement’).

    It’s like using the technique of caching a selector while you use it, except that this will permit caching throughout the life of the script, instead of selecting the element, caching, doing work, then coming back later and selecting the element again.

  • Mah

    So is its important that data that should be secured should not be stored in the data object is it? and if they need to be stored, they need to be encrypted right?

  • Uli Hecht

    “Due to the way browsers interact with plugins and external code, the .data() method cannot be used on <object>, <applet> or <embed> elements.”

    this is even the case for those tags, if being used in xml-files.
    i think it's important to mention that because i searched hours for the cause of an issue when i used jQuery to load an xml-file which contains <object>-tags for a different purpose.

  • ViperArrow

    Actually, all you have to do is use Firebug’s console, and type $(‘selector’).data(), and the object will be printed in the console.

  • ViperArrow

    Yes; anyone accessing your page can easily access the data, with Firebug for example.

  • Jared Jacobs

    I just ran into this same issue. It’s actually worse than you said. Using .data(object) doesn’t cleanly remove event bindings; rather it breaks them. The event bindings remain. The jQuery machinery that fires off event handlers just breaks because it assumes that some event-related data is still there under the “events” data key.

    For me, the JS error looks like this:
    TypeError: Cannot read property ‘submit’ of undefined

    The line that triggers it is this line from jQuery.event.handle:
    var events = jQuery.data(this, “events”), handlers = events[ event.type ];

    I’ve just filed a bug about it. http://dev.jquery.com/ticket/6556

  • http://albsource.com haknick

    The data is not stored on the element. It's actually stored in $.cache

  • http://www.jacobkking.com Jake

    The documentation doesn’t say anything about setting an object’s property in .data().

    Example:
    var object = {foo: ‘bar’}
    $(myElement).data(‘someObject’, object);

    What if I want to add another property to ‘someObject?”

    $(myElement).data(‘someObject.secondFoo’, ‘secondBar’);

    To my knowledge, this throws an error.

  • http://www.jacobkking.com Jake

    The documentation doesn’t say anything about setting an object’s property in .data().

    Example:
    var object = {foo: ‘bar’}
    $(myElement).data(‘someObject’, object);

    What if I want to add another property to ‘someObject?”

    $(myElement).data(‘someObject.secondFoo’, ‘secondBar’);

    To my knowledge, this throws an error.

  • http://www.learningjquery.com/ Karl Swedberg

    You would need to get the value of that data object, set the new property, and then set the object as the value again:

    // data has already been set. now retrieve it...
    var someObject = $(myElement).data('someObject');
    // set the new property
    someObject.secondFoo = 'secondBar';
    // set the data again
    $(myElement).data('someObject', someObject );

  • http://www.jqueryrefuge.com/ John Strickler

    Are there any plans of making HTML5′s custom data- attributes accessible via .data()? The specification allows easy access through an element’s .dataset property but this is pretty unreliable right now since it’s not really implemented in many browsers.

    Currently, I’m using a plug-in to retrieve all custom data attributes and make it accessible through .data().

  • http://www.jqueryrefuge.com/ John Strickler

    If the DOM element is removed using .remove() then the data from the cache IS deleted as well even though it is stored separately at a central location.

    If you want the data to remain then use .detach() to temporarily remove the DOM element.

    Hope this helps.

  • http://profiles.yahoo.com/u/CEQ4CHVRUWBUWKDWDSELXDFNZU Gavin

    So if the dom element is deleted, the data is not actually lost or freed?

  • Moe

    Any recommendations on the use of .data() compared to .addClass() for storing booleans on elements etc.? I’m thinking performance wise is .addClass(‘clicked’) faster than .data(‘clicked’, true) for instance?

  • Anonymous

    addClass() is fast, no doubt. It rebuilds the className string every time it is called. Data is dealing directly with the jQuery cache if that tells you anything about its performance then you know its going to be just as quick. Unfortunately, I don’t have any hard numbers for you right now but the performance difference is negligible, imho.

    On a side note: data() is more flexible because you can do beyond boolean values, also, its a step in the right direction to get away from using the class attribute to store data.

  • Bluescrubbie

    It says above that an empty string is returned if no value is set for the given key. Under 1.4.2, I’m getting null on unset values.

  • https://me.yahoo.com/a/ofIT_8h3nNG.Hxh1XSmK.riRLUdmg5o-#90c89 Raphael

    It should not be necessary to set the data again after adding a property since the data() getter does not return a copy but the actual object.

  • http://www.ciftcioglumobilya.com/kose-takimlari.htm Köşe Takımları

    If you want the data to remain then use .detach() to temporarily remove the DOM element.

  • http://twitter.com/marlosin Marlos Borges

    It’s important that the key’s not a number, it doesn’t work.

  • Arno_schaefer

    In 1.3.2, the return value is undefined on unset values, in 1.4.2 it is null. Neither return the empty string.

  • http://portonvictor.org Victor Porton

    What happens if we call x.data(‘name’) where x is a set of SEVERAL elements? What it returns, an array?

  • http://pulse.yahoo.com/_3MZVJOFRSEPW3FYCIGYYNYC44U Drew

    Does this play nicely with HTML5 'data-' attributes? I want to bake some info into my DOM when generating HTML, and have that available from jQuery.

    For example:

    <div id=”test” data-foo=”bar”></div>

    var foo = $('#test').data('foo');

    It doesn't seem to work for me with jQuery 1.4.2. Is there an alternative API for this? Am I missing something? This would be a very useful technique, whatever the access method.

  • Misoks

    I have problem to set .data for multiple element:
    i.e. $(“#elem1,#elem2,#elem3″).data('foo')._renderItem = function()… blabla

    …but It set _renderItem only for first element

  • http://www.learningjquery.com/ Karl Swedberg

    Not yet, but there are a couple patches that are being considered for future versions of jQuery. In the meantime, the metadata plugin might do what you need.

  • http://www.learningjquery.com/ Karl Swedberg

    You can loop through the elements with .each() and set data to each one individually.

  • http://www.learningjquery.com/ Karl Swedberg

    As the description states: “Returns value at named data store for the first element in the jQuery collection, as set by data(name, value).” (emphasis added)

  • Jason Kostempski

    Does add/changing/removing a data value trigger an event I could subscribe to? It would really tickle me pink if there is.

  • Anonomom

    If I remember correctly, I read somewhere the “data facility” internally uses a unique ID per DOM element.

    If so, I'd really like to see that ID to be publicly accessible – not only because it is mentioned in the docs, but also because it is useful to have, e.g. to key drag/drop targets within a complex widget. Ideally the documentation of the envisioned function would provide some hints on how to create sub keys without causing name clashes.

  • http://twitter.com/The_Mighty_Zeus Jason Brown

    Like Karl said, you can use .each(). You can use .data() to set data on all items in a collection at once, but you're actually retrieving data and then performing operations on the result. Like most functions that return a value other than the jQuery collection, when used to retrieve data, the .data() function will only return the data for the first matched element.

  • Philipp

    you could use $.extend for that case:

    $.extend($(myElement).data('someObject'), {

    secondFoo, 'secondBar'

    })

  • http://twitter.com/bosmonster_nl Paul van Dam

    Note the subtle change in quotes when trying to access JSON notation from data-attributes. This will not work the other way around.

    Also noteworthy is that it will not update the attributes after you change or set via data(). It is one way traffic only.

  • http://twitter.com/wbreza Wallace Breza

    I noticed this as well. If you want to use JSON, the string must be a valid JSON string since internally it uses jQuery.parseJSON. This means that property keys must be surrounded by quotes as well.

    Also note that javascript objects are not parsed from the string, so if you expect to wire up to a function on your page within an attribute it will not work.

    I thought this would replace the use for the metadata plugin, but it's limited to pure JSON strings.

  • http://twitter.com/timmolendijk Tim Molendijk

    I am missing documentation on the setData/getData/changeData events. See also http://forum.jquery.com/topic/setdata-getdata-events-should-be-capable-of-overriding-data-s-default-behavior-but-how

  • DB

    Hi,

    I'm getting some odd results that I'm not expecting when using the data function where it is extending objects.

    EG

    var myObj = {foo:”bar”};
    var newobj = myObj;
    $(“body”).data(“params”,newobj);
    $(“body”).data(“params”).lorem = “ipsum”;

    console.log(“body”,$(“body”).data(“params”));
    //contains foo and lorem as you'd expect
    console.log(“newobj”,newobj);
    //contains foo as you'd expect but also contains lorem
    console.log(“myObj”,myObj);
    //contains foo as you'd expect but also contains lorem too.

    Can anyone explain why this is? Is this expected behaviour or a bug? I'd expect it to leave newobj alone.

  • Me

    myObj and newobj both point to the same object.

    See http://api.jquery.com/jQuery.extend/ for how to copy objects.

  • http://pulse.yahoo.com/_NWWNAEX5IY45ZDJEGTURQOCXEQ Goulven

    This has been said in previous comments but I believe it should be plainly explained in the documentation:
    When using JSON in data attributes, jQuery expects double quotes around labels. If you get a string instead of an object, make sure that you've used double quotes for the labels inside, and simple quotes for the whole JSON string.

    Valid code (data('value') returns an object):
    <tag data-value=”{“double-quote label”:”works”}”>

    Invalid code (data('value') returns a string):
    <tag data-value=”{'simple-quote label':'does not work'}”></tag></tag>

  • Yy_model

    晕,能不能说中文啊

  • user

    中文在哪里 在哪里

  • df

    Good point. Please note that in general JSON format specifically consists of having those double quotes, without them you are writing non-standardized JSON.

  • Mail2krishnam

    $(“#”+active_element).data(“default”,{“ele_title”:”untitled”,
    “ele_type”:”text”,
    “ele_size”: “medium”,
    “ele_guidelines”: “”,
    “ele_Min”:”0″,
    “ele_Max”:”",
    “ele_Format”:”character”,
    “ele_is_required”: “0″,
    “ele_is_unique”: “0″,
    “ele_is_private”: “0″,
    “ele_type”: “text”,
    “ele_default_value”: “”,
    “ele_instruction”:”",
    “ele_classnames”:”"
    } )

  • DB

    I ended up extending the equivalent of newobj with a local object instead. If it helps the code above is the pared-down version of what I was doing, newobj was actually this.savedSearch which was used throughout an object.

    The gotcha here for me was that changing $(body).data(“params”) also updated newobj. So does the data function create a reference rather than extend the data's object?

  • Justin

    Hello,

    Just wondering if we can add this to part of the documentation?

    We have this:
    .data( key, value )
    .data( obj )

    I think we should also include:
    .data( key, obj )

    I was trying to attach JSON data via .data(obj) but obviously it didn't work out that well.

  • http://www.learningjquery.com/ Karl Swedberg

    If you look at the available types for “value,” you'll see that one of them is Object.

  • Declan

    Why doesn't .data() have support for a function as the second argument? It is very similar to .attr() and this functionality (haha) makes sense.

  • Geordie Korper

    That it reads from HTML 5 data- attributes but does not write back to them should probably be noted in the Description.

  • Declan

    Why doesn't .data() have support for a function as the second argument? It is very similar to .attr() and this functionality (haha) makes sense.

  • Geordie Korper

    That it reads from HTML 5 data- attributes but does not write back to them should probably be noted in the Description.

  • daan

    When you store an array using data, you can manipulate that array using normal array functions like array.push(). Saving the manipulated array is not necessary since arrays are passed by reference, not value. It still was something I did not expect..

    e.g.:
    element.data('test').push('new');

  • damir

    What about anonymous data? Can't find anything about it, but I've found a few examples using it something like this $.data(this, “example”, true);

    Can somebody explain what 3 values do in data? Thanks!

  • Raphael

    I need to know if a plugin was already initialized. In according to the plugin authoring doc, I should use the data method. So, in my plugin, I put a boolean flag using the data method to do that.
    But what happens if the plugin user put that flag in the tag like “<div data-initialized=”true”>” ?

    My plugin would be broken, right? Is there some safer way to do that?</div>

  • Michael Probst

    hdfg

  • Joshaven

    First, setting data doesn't set attributes…
    Secondly, you can use a variable that is unlikely to be use by someone else like:
    $('body').data('jQuery_myCoolPlugin', 'initialized')
    if ($('body').data('jQuery_myCoolPlugin') != 'initialized') {/*do something*/}

  • Joshaven

    The use of three values is because the first variable is the element that the data is being stored in… try this working example:
    el = $('body').get(0);
    $.data(el, “example”, 'Hello World');
    $('body').data('example');

  • Yourtech

    The second argument can be a function.
    $('body').data('tryMe', function() {return 'Hello World'});
    $('body').data('tryMe')();

  • Joshaven

    This can be done through the following:
    json = {one:1, two:2};
    for (key in json){ $('body').data(key, json[key]) }
    $('body').data('two');
    //=> 2

  • http://twitter.com/IndigloMouth Ryan Kinal

    When using .data where the value is a function, it seems that the value of `this` inside that function is the containing window. It would be awesome if it were the element instead, but that is not the case.

  • http://twitter.com/IndigloMouth Ryan Kinal

    As Joshaven says, the second argument can be a function. However, the value will be the function, not the return value of the function as is true with .attr(). While I agree that it might be useful to have similar functionality in .data(), I think it's Joshaven's example that prevents it – .data() may be used to store a function which can be called later in execution.

    I'd suggest using .each() in combination with .data() to get the functionality you're looking for.

  • Alex

    > The data is not stored on the element. It's actually stored in $.cache

    Since data is not stored in the element, there's no way to generate html with predefined data accessible with jquery's .data() function (without use of html5 'data-' attributes)? The only way to add data to elements is to use javascript which adds some data lets say on dom ready event? Am I right?

  • https://www.google.com/accounts/o8/id?id=AItOawlYHmUOtJHeoIjVtmAyNIyP3XgOk-ue9gw Nyuszika7H
    // alerts out 'Hello, world!'$('body').data('test', alert('Hello, world!'));// returns undefined$('body').data('test');