5

I have a button that grabs some data from the server using ajax, and when it's done, it it supposed to add a element to the DOM.

The element to add will be something like this

<div class="SomeClass">
  <div class="SomeOtherClass">
    <span class="Name">name from server</span>
    <span class="Manufacturer">manufacturer from server</span>
  </div>
  <span class="Weight">weight from server</span>
</div>'

In my jQuery function that gets the data back from the server, what is the best way to create this structure, put the data (name, manufacturer and weight) from the server in at the correct places, and put it into the DOM. I have got it working like this:

$("#ItemList").append('<div class="SomeClass"><div class="SomeOtherClass"><span class="Name">' + value.name + '</span><span class="Manufacturer">' + value.manufacturer + '</span></div> ' +
                       '<span class="Weight">' + value.weight + '</span></div>');

But this does not look very good, and it's hard to see the proper structure.

What is the best way of doing this in a clean manner?

Øyvind Bråthen
  • 59,338
  • 27
  • 124
  • 151
  • 1
    use http://aefxx.com/jquery-plugins/jqote/ plugin. Its faster than jquery template plugin. Makes client side templating easy. –  Jun 15 '11 at 08:24

6 Answers6

19

If i needed multiple "version" of the structure I would go with adding something like

<div class="SomeClass" id='SomeClassTemplate' style='display:none'>
   <div class="SomeOtherClass">
      <span class="Name">name from server</span>
      <span class="Manufacturer">manufacturer from server</span>
   </div>
   <span class="Weight">weight from server</span>
</div>

at the bottom of my html body, and then inside my the event handler where the element is to be added i would do

var newDiv = $("#SomeClassTemplate").clone();
newDiv.attr("id","whatever") 
// remember this id should be different for each instance. or you can remove it
.appendTo("whatever") // depends on where in DOM you want to insert it
.find(".name").html("My name");

newDiv.find('.manufacturer').html("my manufacturer);
newDiv.show();

The advantage i found with this approach is that this code can easily be modified by tweaking the selectors in case the structure changes.

kyushiro
  • 240
  • 2
  • 7
  • +1: I ended up using a variation of this one. The html of the element to insert gets very clean and is easy to visualize and change. – Øyvind Bråthen Jun 16 '11 at 05:53
  • Only if I know i`ll use this DOM in my page, i`ll integrate it already in the template, and than populate the content. In many cases I will inject content based on conditions, than this approach will not fit my needs. – neoswf Nov 30 '13 at 20:24
6

If you want to keep readability in mind then the following approach is both clean and doesn't perform any unnecessary jQuery lookups to add the content.

var div = '<div class="someClass">' +
          '    <div class="SomeOtherClass">' +
          '        <span class="Name">' + value.name + '</span>' +
          '        <span class="Manufacturer">' + value.manufacturer + '</span>' +
          '    </div>' +
          '    <span class="Weight">' + value.weight + '</span>' +
          '</div>';

$('#itemList').append(div);
Jonathan Reyes
  • 94
  • 2
  • 12
amustill
  • 5,274
  • 23
  • 15
1

The way I am doing is shown bellow. I am not sure if u should create so many divs but it worked pretty well with me.

var div1 = $('<div class="colwrap_fof"></div>');        //THE COMPLEX DIV ITSELF
var div2 = $('<div class="homeimg"></div>');                
var div21 = $('<div id="backImageDiv'+fof_index+'" class="backDiv"></div>');
var div22 = $('<div id="frontImageDiv'+fof_index+'"  class="frontDiv"></div>');
div2.append(div21);
div2.append(div22);
div1.append(div2);
$("#df_background").append(div1);     // ADDING the complex div to the right place      

Cheers,

marcelosalloum
  • 3,481
  • 4
  • 39
  • 63
1

You could use the jQuery template plugin. But if this is the "best" way, I can't say. Using templates requires more processing time, but the code is more readable. You have to weigh up for your specific task. But note that it’s now deprecated as per Recommended JavaScript HTML template library for JQuery?

Community
  • 1
  • 1
DanielB
  • 19,910
  • 2
  • 44
  • 50
0

maybe you can try out jQuery Templates ?

It is still in beta, but I believe that it is widely used.

(Example is from the documentation)

<!DOCTYPE html>
<html>
<head>
  <style>
table { border-collapse:collapse; margin:8px; background-color:#f8f8f8; }
table td { border:1px solid blue; padding:3px; }
</style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
  <script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
</head>
<body>

<button id="showBtn">Show movies</button><br/>
<table><tbody id="movieList"></tbody></table>

<script>
  var movies = [
  { Name: "The Red Violin", ReleaseYear: "1998", Director: "François Girard" },
  { Name: "Eyes Wide Shut", ReleaseYear: "1999", Director: "Stanley Kubrick" },
  { Name: "The Inheritance", ReleaseYear: "1976", Director: "Mauro Bolognini" }
  ];

var markup = "<tr><td colspan='2'>${Name}</td><td>Released: ${ReleaseYear}</td><td>Director: ${Director}</td></tr>"

/* Compile markup string as a named template */
$.template( "movieTemplate", markup );

/* Render the named template */
$( "#showBtn" ).click( function() {
  $( "#movieList" ).empty();
  $.tmpl( "movieTemplate", movies ).appendTo( "#movieList" );
});
</script>

</body>
</html>
0

You can use jQuery template as DanielB suggested, you code will look cleaner and *probably easier to maintain but think about adding yet another script which is in beta mode to your application. Is it worth it?

I work this way, if HTML must be dynamic via jQuery or it is small chunk of code like <div>Hello</div>, i would use selector.append().

if it is HTML code like in your example i would stick to keeping it on HTML page as it is.

To me it really a question of what you should do with HTML next.

For example i've been using jQuery templates in online chat application i've been working on which did in fact helped me with maintenance.

eugeneK
  • 10,750
  • 19
  • 66
  • 101