guub guub - 1 year ago 74
jQuery Question

Store data on element before appending

I want to store JSON on an html element using jquery

. However my elements are actually an html string and are not yet in the DOM like so.

$(".test").each(function() {
el += "<span>"+ 25 +"</span>";


I have tried this (within each function)

el += $("<span>"+ 25 +"</span>").data("test", {"name":"john"});

But when I append
, I get
appended instead

How can I associate the data with the element and be able to retrieve it after its appended?


Answer Source

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:"test").name.


Based on your example code, I've updated your fiddle with working code. See the comments for the explanation..

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"});

   var data = $(this).data("test");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download