2

I have Googled my question multiple times, with different phrases, and have either gotten answers that don't work, asdign the element to a variable, or only work with one variable.

What I am trying to find out is if it is possible to assign objects to elements, and if so, find out how to do so and be able to retrieve that data for (in my case) an append() call. I have tried using data(), but I could not find any way to pull the data back out for the append() (none of the tutorials I found had any mention of displaying the data).

Any help is greatly appreciated.

TNTftw21
  • 21
  • 4

2 Answers2

1

If I understand your question, you wish to assign a jQuery object in a html element. I think than you can serialize object as JSON and later parse this.

You can use this: https://github.com/douglascrockford/JSON-js like described in: Serializing to JSON in jQuery

var jsonString = JSON.stringify(jqueryobject);

And to recover object:

var object = JSON.parse(jsonString);

I tested this without jquery library cited and work too.

Community
  • 1
  • 1
gabrieloliveira
  • 560
  • 3
  • 10
  • I honestly haven't used JSON yet (I only got into web design 4-5 months ago), but I'll give this a shot. – TNTftw21 Mar 30 '14 at 03:03
0

Use .html():

var dataToAppend = $("<h1>I'm appended!</h1>");
$("body").append(datatoAppend.html());

If you need an element with the outer HTML, just select an outer wrapper element:

var dataToAppendOuter = $("<div><h1>I'm appended!</h1></div>");
$("body").append(dataToAppendOuter.html());

EDIT:
Here is a jsFiddle to hopefully better illustrate what I was trying to explain above. Of course there are some assumptions I am making, so some clarification in the question would be beneficial, as I may be misunderstanding the needs.

Tim Hobbs
  • 2,017
  • 17
  • 24
  • I'm not trying to save HTML to a variable and append the variable. What I am trying to do is set up a system that allows me to save jQuery data (like a boolean), and then, when someone hovers over the element, the jQuery uses the data that was attached to the HTML and appends that. What I am designing is something where you hover over a picture (for a game), and data about the picture is produced and appended to a div. – TNTftw21 Mar 30 '14 at 03:02
  • It was simply an example. The selector can be an existing element or you can create it yourself. You included no code in your question, so I had nothing concrete to work with, hence the example. Based on what you are saying it would work as I explained, assuming the "data that was attached" means non-visible HTML. Otherwise you'll need to explain more and possibly provide examples. Try linking a jsfiddle to illustrate. – Tim Hobbs Mar 30 '14 at 08:07