Reputation:
I want to store JSON on an html element using jquery data()
. However my elements are actually an html string and are not yet in the DOM like so.
$(".test").each(function() {
el += "<span>"+ 25 +"</span>";
});
$("body").append(el);
I have tried this (within each function)
el += $("<span>"+ 25 +"</span>").data("test", {"name":"john"});
But when I append el
, I get [object][object]
appended instead
How can I associate the data with the element and be able to retrieve it after its appended?
FIDDLE: https://jsfiddle.net/6mhgwtk1/1/
Upvotes: 0
Views: 57
Reputation: 23379
You did it right, but it's an object. When you print or alert an object it will always appear as [Object]
. Instead of printing the object print it's properties instead, like this: el.data("test").name
.
see: https://jsfiddle.net/6mhgwtk1/
var el;
$("div").each(function() {
// el is not a string here, (it's a jQuery object) so you can't concatentate it using +=
// instead you will have to append each one to the body separately
el = $("<span>"+ 25 +"</span>").data("test", {"name":"john"});
$("body").append(el);
});
$("body").find("span").each(function(){
var data = $(this).data("test");
console.log(data);
});
Upvotes: 2
Reputation: 930
For retrieving, Try getting attributes of el (since it is an object).
Upvotes: 0