Best way to assign a javascript object to html element

10,517

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.

Share:
10,517
Marc Vilalta
Author by

Marc Vilalta

Updated on June 28, 2022

Comments

  • Marc Vilalta
    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
    Ashith about 10 years
    I 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
    Oscar Paz about 10 years
    Of 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
    Ashith about 10 years
    right 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
    JDC about 3 years
    typo getElmentById => getElementById