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

Dispatching identification to controller after submission

I am encountering an issue with a page that contains the following code: <div class="col-sm-2 displaybutton"> <div data-point-to="displaysHeader"> @using (Html.BeginForm("Administration", "Home", FormMethod.Post)) ...

Is it possible to set up VS Code's code completion feature to automatically accept punctuation suggestions?

For all the C# devs transitioning to TypeScript in VS Code, this question is directed at you. I was captivated by the code completion feature in VS C#. To paint a clearer picture, let's say I'm trying to write: console.log('hello') W ...

Send a JSON object from an AngularJS application to an MVC controller

When attempting to pass JSON data from AngularJS to MVC, an error is encountered. The HTTP request configuration URL must be a string or a trusted $sce object. Error received: {"method":"POST","url":"Home/SavePDDetails","datatype":"json","data":{"PD": ...

Highlighting the current menu item by comparing the URL and ID

Looking to make my navigation menu items active based on URL and ID, rather than href. None of the suggested solutions (like this one, this one, or this one) have worked for me. This is how my Navigation is designed: <nav id="PageNavigation"& ...

Despite the presence of data within the array, the React array returns empty when examined using the inspect element tool

Currently, I'm working on creating an array of objects in React. These objects consist of a name and a corresponding color, which is used to represent the pointer on Google Maps. For instance, one object would look like this: {name: "Ben", colour: "gr ...

Python application for flattening and mapping nested JSON keys

I am completely new to JSON and struggling with understanding the structure of a JSON file. Here is an example of a JSON file I have: {"employeeId":{"0":02100, "1":02101, "2":02102,... "1000000":021000000}, "employeeName":{"0":"Smith", "1":"John", "2":" ...

Issue with Firefox compatibility in Backbone.js

Greetings! I am currently utilizing Backbone.js and require.js for my application, experiencing difficulty with template rendering in Firefox. Interestingly, it works without issues in both Chrome and IE. Allow me to present the code responsible for rende ...

Creating dynamic transformations and animations for characters and words within a paragraph in 3D

Looking to add animation effects to specific parts of a paragraph, but transforming the entire box instead. Remembering seeing a solution on StackOverflow before, now regretting not saving it. Spent over an hour searching for a similar answer without succ ...

Please note: With React 18, the use of ReactDOM.render is no longer supported. Instead, we recommend using create

I encountered an issue while attempting to link my React application with a MongoDB database. Here is the code snippet where the problem occurred: //index.js ReactDOM.render( <React.StrictMode> <BrowserRouter> <App /> &l ...

Can anyone recommend any offline editors for HTML, CSS, and JavaScript similar to JSFiddle, jsbin, or codepen?

Is there an alternative to JSFiddle.net that allows users to experiment with Javascript, HTML, and CSS offline in a similar way? ...

Initiating PHP outcomes with the integration of JQUERY and Bootstrap

Currently, I am working on a Twitter search functionality that allows me to search for any content on Twitter. While the feature is functional, I am facing some challenges with displaying the results in the desired format. Ideally, I would like the results ...

Extracting a subclass from an array

Currently, I am delving into the world of coding as part of a project I'm working on. Here is an excerpt from my JavaScript code that interacts with Google Maps API: for (i = 0; i < results.length; i++) { console.log("Formatted Address: "+ re ...

The jQuery Multiselect filter contradicts the functionality of single select feature

http://jsfiddle.net/rH2K6/ <-- The Single Select feature is functioning correctly in this example. $("select").multiselect({ multiple: false, click: function(event, ui){ } http://jsfiddle.net/d3CLM/ <-- The Single Select breaks down in this sc ...

Positioning Images in Tailwind Modals

I'm currently working on building a modal using Tailwind in Vue, but I've run into some challenges with aligning the elements inside the modal as desired. I've experimented with removing certain Tailwind classes and have tried implementing ...

tilt and give motion to image within canvas

I am looking to incorporate skewing and animation effects on an image displayed on a canvas. While I have successfully drawn the image on the canvas using the code snippet below, I am unsure about how to apply skewing and animation to the image post-drawin ...

Discovering the Secrets of Accessing and Modifying Item Values in BIRT

Is it feasible to create using only Javascript without utilizing any Java functions? Is there a way to access values from elements like labels, tables, or charts by calling them from an HTML button? I am currently working with Openlayers and BIRT. I need ...

AngularJS - Use promise instead of returning a data object

I am currently working on a project using AngularJS. Within my service.js file, I am attempting to retrieve some values. However, instead of receiving the actual data, I am getting back a promise object with some $$variables along with the desired data. ...

Having trouble retrieving the URL from JSON data - every time I attempt to access it, it just shows as undefined. Any suggestions

Having trouble extracting the URL from JSON, as it shows undefined. Any suggestions? <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" ></meta> <script language="JavaScript" type="text/javascript" ...

How can I resolve the "web page not found" error when using jQuery .replace()?

Working on HTML and javascript/jquery scripts, I have encountered a peculiar issue. My script utilizes a for-in loop to iterate through a JavaScript object, substituting specific patterns in HTML-formatted lines with data from the object using jQuery .appe ...

The import component path in Angular 4/TypeScript is not being recognized, even though it appears to be valid and functional

I'm currently working on building a router component using Angular and TypeScript. Check out my project structure below: https://i.stack.imgur.com/h2Y9k.png Let's delve into the landingPageComponent. From the image, you can see that the path ...