Parse and render comments data to UI

by Michael Prosser

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

<ul class="comments"></ul>

CSS

@import url('https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100..900;1,100..900&display=swap');

body{
  font-family: "Roboto", sans-serif;
}
ul.comments {
  list-style: none;
  padding: 0px;
  margin: 0px;
}
ul.comments>li {
  padding: 15px;
  margin: 4px;
  background-color: aliceblue;
  border: solid dodgerblue, 1px;
}
ul.comments>li>p{
  background-color: #fff;
  padding: 10px;
  font-size: 15px;
  margin-bottom: 0px;
  margin-top: 5px;
}
ul.comments>li>label.user{
  color: dodgerblue;
  font-size: 13px;
  font-weight: bold;
}
ul.comments>li>label.timestamp{
  float: right;
  font-size: 11px;
}

JavaScript

/* 

I use Object Oriented Programming when possible 
Most of our UIs consist of endpoint data and a class method to handle the parsing
This is a super simple example where we are going to take comments data and parse it to a page using a class

A Javascript class has a constructor - this is a function and it is called when you create a new instance of a class
so basically it is your startup function. When calling a new instance of our class, you will see we pass 2 parameters
that are also the same 2 parameters in our constructor function.

The parameters are cached into the class as own properties so they can be called from within a class method

We have one class method parseOutput() 

This is a function but you don't have to use the keyword function to defined these in a class, the brackets are all you need.

Inside that function we loop through the data using a let type variable. If you are in a loop, let is best because it is retained in scope differently that var

We use jQuery at the moment for DOM manipulation so we are creating a jquery element using $(some html) within our look and appending it to the body.

*/


class Comments {

  constructor ( outputElement, data ){

    this.data = data;
    this.outputElement = outputElement;

    this.parseOutput();

  }

  parseOutput(){

    let l = this.data.length;

    for(let i=0;i<l;i++){

      let comment = $(`<li>
      <label class="user">${this.data[i].user}</label>
      <label class="timestamp">${this.data[i].timestamp}</label>
      <p>${this.data[i].comment}</p>
      </li>`);

      this.outputElement.append(comment);

    }

  }

}

// we deal with JSON data from API endpoints but you can simulate using a Javascript Object Array

var jsonData = [
  {
    "user": "Michael Prosser",
    "timestamp": "2025-08-01 21:05:15",
    "comment": "This is great!"
  },
  {
    "user": "Frank Byers",
    "timestamp": "2025-08-01 20:33:31",
   ...