Generate div elements dynamically for each object being populated in JSON using JavaScript

I have a main container that displays a list of JSON objects. Each object should be displayed as a separate DIV element with specific details, one after the other.

Additionally, I have a comments section on a webpage where the details are stored in JSON format as {author, id, comments, time}. I am looking to extract all the comments for a particular page and display them within a single DIV. Each comment will be represented as a child Div (showing the author's name, comment content, and timestamp) inside a parent DIV.

Answer №1

HTML Code

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
  <!--<script src="app1.js"></script> -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/js/bootstrap.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"/>

</head>

<body> 
  <div id="placeholder1"></div>
  <div id="placeholder2"></div>
  <script>
    var data={
      "firstName":"Ray",
      "lastName":"Villalobos",
      "joined":2012
    };

    var data1={
      "firstName":"John",
      "lastName":"Doe",
      "joined":2013
    };
    document.getElementById("placeholder1").innerHTML=data.firstName+" "+data.lastName+" "+data.joined;
    document.getElementById("placeholder2").innerHTML=data1.firstName+" "+data1.lastName+" "+data1.joined;
  </script>

</body>
</html>

Answer №2

One of the challenges lies in locating a sufficiently large DIV to accommodate all the data. Most DIVs are of standard size and therefore not suitable for this specific application. ;)

The following code snippet retrieves Yahoo weather information, converts the key-value pairs into text, and presents each piece within a distinct DIV contained in the LARGE DIV.

update: Slightly adjusted according to the new requirements from the original poster.

Execute the code snippet to observe it in action:

<html>
<body>
 <link href='http://fonts.googleapis.com/css?family=Permanent+Marker' rel='stylesheet' type='text/css'> 
<style type="text/css">
div {padding: 4px;border: 1px red dotted;font-family: monospace;font-size: 10px;}
    h2 {font-family: 'Permanent Marker', cursive; font-size:24px; color:steelblue;}
</style>
<h2>A REALLY SUPER BIG DIV WITH DATA</h2>
<div id="BIG_DIV"></div>
<script type="text/javascript">

function callback(data) {
document.getElementById('BIG_DIV').innerHTML = getKeys( data );
}

function getKeys( obj ) {
var key, html='';
for( key in obj) {
if (typeof obj[key] == 'object') html += '<div>' + getKeys( obj[key] ) + '</div>';
else html += '<div>' + key + ':' + obj[key] + '</div>';
}
return html;
}

</script>
<!-- Yahoo Weather data -->
<script type="text/javascript" src='https://query.yahooapis.com/v1/public/yql?q=select * from weather.forecast where woeid in (select woeid from geo.places(1) where text="Paris")&format=json&callback=callback'></script>
</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to retrieve a specific attribute within a detailed JSON reply

I have implemented cloud code in ParseServer - Back4app, which utilizes node.js to send a request for Football API. The axios request returned the following result: { "result": { "get": "teams", "param ...

Clicking two times changes the background

I am facing an issue with three boxes on my website. Each box is associated with a corresponding div. When I click on any box, the div displays and the background color turns red. However, when I click on the same box again, the div disappears but the back ...

Creating multiple asynchronous calls within a loop in JavaScript

I am currently working on a task in my gulpfile.js that involves uploading an app using Gulp and SharePoint. 'use strict'; const gulp = require('gulp'); const build = require('@microsoft/sp-build-web'); const spsync = require ...

Having trouble retrieving text from an HTML form in Node.js using express, as the req.body object is coming up

Having trouble extracting text from an HTML form to build a basic text to speech functionality. Despite using an express server, the req.body is consistently empty when attempting to fetch the text. I've experimented with body-parser and adjusted the ...

The Next.js app's API router has the ability to parse the incoming request body for post requests, however, it does not have the

In the process of developing an API using the next.js app router, I encountered an issue. Specifically, I was successful in parsing the data with const res = await request.json() when the HTTP request type was set to post. However, I am facing difficulties ...

Tips for concealing the bar graph while maintaining the visibility of the data labels in HighCharts

Is there a way to hide one bar but keep the data labels in HighCharts? I have 3 bars: Target Realization Percentage I want to display only the first and second bars, with only 1 data label which is the percentage. So, I made some adjustments to my co ...

Suggestions for relocating this function call from my HTML code

I have been working on updating a javascript function that currently uses an inline event handler to a more modern approach. My goal is to eliminate the unattractive event handler from the actual HTML code and instead place it in a separate modular javascr ...

Implementing a function in jQuery to create a "Check All" and "Uncheck All" button

Can someone please guide me on how to implement a check all and uncheck all functionality when I check individual checkboxes one by one? Once all checkboxes are checked, the 'checkall' checkbox should automatically be checked. Below is the code s ...

What are the best scenarios for implementing anonymous JavaScript functions?

I am currently exploring the reasons behind using anonymous JavaScript functions. Can you list out the distinctions between these functions? Describe scenarios where each function would be appropriate to use. var test1 = function(){ $("<div />" ...

The persistent connection of Socket.io results in consecutive connections while disregarding other occurring events

My goal is to create a unique web application where users can engage in toroidal chess matches with one another. This is the code from my app.js file on the server side: var express = require('express'); var app = express(); var http = require(& ...

What is the best way to transform a UTC/GMT date and time into CST in Javascript? (CST specifically, not based on

Dealing with a tricky situation where backend data is always stored in UTC time while our front-end data is in CST. Unfortunately, I don't have access to the system handling this 'black box' conversion. Trying to replicate this setup in our ...

Executing a function on page load instead of waiting for user clicks

I've been researching a problem with onclick triggers that are actually triggered during page/window load, but I haven't been able to find a solution yet. What I need is the ID of the latest clicked button, so I tried this: var lastButtonId = ...

What is the best way to create a JSON array in Grails as described below?

Can someone please guide me on how to create a JSON array using Grails? Here is what I have attempted: {"paymentRequestlist":[{"sourceAccountNo":"555555555555555","sourceBankCode":"GLBBNPKA","destinationBankCode":"GLBBNPKA","destinationBankAccountNo":"123 ...

What is the best way to determine the width of a CSS-styled div element?

Is there a way to retrieve the width of a div element that is specified by the developer? For example, using $('body').width() in jQuery will provide the width in pixels, even if it was not explicitly set. I specifically need to access the width ...

How can I extract data from a unique JSON object using .Net?

I'm working on an ASP.Net application that requires me to interact with a HTTP REST API which responds with a JSON object. The structure of the JSON response is as follows: message: [ { type: "message" href: "/messages/id/23" view_hre ...

Determine the file format using fs module in Node.js

I have a question about extracting file types or extensions from a folder. I have multiple files in a folder, and I want to retrieve the type/extension of the file that matches a randomly generated number stored in my num variable. Is there a way to achiev ...

Can you explain the technical distinctions between Express, HTTP, and Connect?

const express = require("express") , app = express() , http = require("http").createServer(app) As I observe, these dependencies are commonly used. As far as I understand it, http serves front-end HTML, while express manages server-side Node.js logic. ...

Angular: Exploring the differences between $rootScope variable and event handling

I have a dilemma with an app that handles user logins. As is common in many apps, I need to alter the header once the user logs in. The main file (index.html) utilizes ng-include to incorporate the header.html I've come across two potential solution ...

VueJS and Vite: Encountering an unexpected character '�' while attempting to import files that are not JavaScript. Keep in mind that plugins are required for importing such files

I'm puzzled by the error message I'm receiving: [commonjs--resolver] Unexpected character '�' (Note that you need plugins to import files that are not JavaScript) file: /..../..../WebProjects/..../ProjectName/node_modules/fsevents/fse ...

Set the key for all elements in a sibling array to be the same key

Here is a sample input JSON: { "some_key": "x", "another_key": "y", "foo_id": 123, "all_foo": [ { "foo_name": "bar1" }, { "foo_name": & ...