tags:

views:

141

answers:

1

Hi

all is said in the title, I want to get from an element all the data set using the data method.

(ultimately I want to copy that data over to a newly created element)

thanks for any help !

Olivier

+3  A: 

This has been asked before. My answer from there, since it is a good question:

jQuery stores all the data information in the jQuery.cache internal variable. It is possible to get all the data associated with a particular object with this simple but helpful plugin:

jQuery.fn.allData = function() {
    var intID = jQuery.data(this.get(0));
    return(jQuery.cache[intID]);
};

With this in place, you can do this:

$('#myelement').data('test1','yay1')
               .data('test2','yay2')
               .data('test3','yay3');

$.each($('#myelement').allData(), function(key, value) {
    alert(key + "=" + value);
});

Alternatively, you can simply store an object:

$('#myelement').data('data', {test1:'yay1',test2:'yay2',test3:'yay3'});
Paolo Bergantino
Thank you for finding what I was looking for! How ironic that the two of us were the ones trying to find it, since we answered the original :)
matt b
great ! Thanks Paolo
Olivvv
@Oli: No problem. @matt b: Yeah, google search works wonders over stackoverflow search, just do site:stackoverflow.com jquery all data and the old question comes up first. It's like magic!
Paolo Bergantino
I'm not sure but I suspect the plugin to retrieve "too much" data, data that I haven't set but data that is used internally by jQuery. It is still a bit confused for me but I think that somehow jQuery is storing expando's with one element's data. So allData retrieves it too, giving me value/keys such as : jQuery12345197113605 / 572. that thing "jQuery12345197113605" is a uniqueid, so it seems difficult to filter out efficiently. That's all what I have for now.
Olivvv
@Olivvv: I don't think there's any way to differentiate between data that you have set and data that jQuery has set. If this is a problem, you should just go with the second suggestion of storing elements in an object. If that is unacceptable, you can try filtering out any variables that start with jQuery.
Paolo Bergantino
Do you know why and when jQuery is adding this data ?
Olivvv
No, I'm afraid I don't. Sorry.
Paolo Bergantino