Alternatives for appending a div from a JS object

Posted on

Problem

I’ve built my first “real” web app which uses both server-side and client side functions to populate a list of courses a user can register for. Currently, the client receives an Object with the following structure:

Object

{
  "date": "1/1/2018",
  "time": "14:30",
  "title": "String Title 1",
  "desc": "A long string description with information about the workshop.",
  "cat": "Category 1, Category 2",
  "seats": "20",
  "type": "In Person",
  "location" : "Building A",
  "lock": true,
  "code": "ABCD",
  "hash": "Str1ng",
  "who": "Teachers, Admin"
} ...

Then, the client adds div elements built from the Object. I’m using .append() and inserting object keys at the correct point. It works fine, but I’m feeling like this is a really inefficient and frankly, messy, way to add the content.

Client script

var data = JSON.parse(Object);

$("#list").append(
    "<div class='row' id='" + data[j].hash + "'>
       <span class='time'>" + data[j].time + "</span>
       <span class='date'>" + data[j].date + ", </span>
       <input type='checkbox' name='wkshp' value='" + data[j].hash + "'/>
       <span class='title'>" + data[j].title + "</span>
       <span class='desc'>" + data[j].desc + "</span>
       <div class='meta'>
         <span class='loc'>" + data[j].location + "</span>
         <span class='who'>" + data[j].who + "</span>
         <span class='cat'>" + data[j].cat + "</span>
         <span class='type'>" + data[j].type + "</span> 
         <span class='seats'>Seats: " + data[j].seats + "</span>
       </div>
       <div class='reg-code lock hide'>
         <h2>Registration Code</h2>
         <input type='text' name='code' value='' />
       </div>
  </div>"
);

What improvements can I make to the Object? Is there a better way to parse the object by the client?

Solution

  • You could use template literals to avoid the breaking the strings with + and doing to newline. Alternatively, you could use template libraries which are more flexible. Mustache is a good example.

  • Consider using a web framework that does the bulk of the rendering for you. That way, you only have to worry about your data. Web frameworks also do optimizations to avoid re-rendering the entire chunk of HTML, do housekeeping, etc.

Other than that, there’s not much to review.

Leave a Reply

Your email address will not be published. Required fields are marked *