guub guub - 5 months ago 16
jQuery Question

Store data on element before appending

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/

Answer

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/


Based on your example code, I've updated your fiddle with working code. See the comments for the explanation.. https://jsfiddle.net/6mhgwtk1/3/

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