Best way to assign a javascript object to html element
Solution 1
If use JQuery you could use the data storrage functionallity
See data documentation of JQuery
//To store value or obj:
$("#myDivId").data("myKey", valueVar);
//Later to load:
var fetchValue = $("#myDivId").data("myKey");
Solution 2
The easiest way is to do this:
<div id="myDiv">...</div>
In javascript
var myDiv = document.getElmentById('myDiv');
myDiv._variable = variable;
You can recover this later if you want, simply using the same myDiv variable, or, again, with document.getElementById()
or any other DOM method that returns the element.
var variable = myDiv._variable;
The downside of doing it this way is that you can't specify, in the server, or from the markup, which object you want to attach to the element.
Marc Vilalta
Updated on June 28, 2022Comments
-
Marc Vilalta almost 2 years
I'm getting a javascript object via ajax. I need to attach this object to a div in order to be recovered later, for example, on a click event.
If instead of an object I had a variable I would push it into the html tags like this:
'<div variable="'+value+'"></div>';
And I would recover its value like this:
var value= $(this).attr('variable')
Could you suggest me a good approach to do that with objects?
Thank you very much!
-
Ashith about 10 yearsI think this is the best approach if the json object needs to be kept with the element in question. The name of the property that the JSON is stored could be something that signifies the object so that more than one can be attached, like
myDiv.objectA = variable;
-
Oscar Paz about 10 yearsOf course, I'd use a property name with meaning. I used
_variable
in the example because I don't know what exactly @marc-vilalta wants to store. -
Ashith about 10 yearsright on. I just wanted it to be clear that
_variable
didn't have special meaning and also that your downside isn't really such a downside since the OP's question doesn't indicate that the object reflects where it's going to go no matter what solution is used. -
JDC about 3 yearstypo getElmentById => getElementById