Skip to content Skip to sidebar Skip to footer

Best Way To Assign A Javascript Object To Html Element

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 vari

Solution 1:

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.

Solution 2:

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 3:

Using a template engine would be the best approach, dividing logic from view, and that way you can parse full object properties to an html.

in this example i use jQuery & UnderscoreJs template engine.

javascript part:

 $(document).ready(function(){
     var user = { name:"Ofer", age:"29" }

     var markup = _.template($("#userTemplate").html(), user);
     $('#userContainer').html(markup);
});

html part(goes inside body)

<divid="userContainer"></div><scriptid="userTemplate"type="text/template"><fieldset><legend>User</legend>
 Name: <%= name %><br>
 Age: <%= age %> <br></fieldset></script>

The function _.template($("#userTemplate").html(), user); can be called from within the complete callback function of the ajax, passing the data from the results to the function (user variable would be the data)

Solution 4:

Using https://api.jquery.com/prop/

yourObj = [];

//now fill your object with your data$row = $("td.yourClass")

$row.prop("dataObj", yourObj );

Post a Comment for "Best Way To Assign A Javascript Object To Html Element"