Ways to dynamically update a div with data from a JSON response

I'm currently in the process of developing a search platform. I have three static divs on the search results page that display certain content, all containing similar code.

For example:

<div id="result" class="card">
<img src="hello.png" class="card_img" alt="result image">
<h4>OFFLINE</h4>
<p>Yes!!</p>
</div>

<div id="result" class="card">
<img src="hello.png" class="card_img" alt="result image">
<h4>OFFLINE</h4>
<p>Yes!!</p>
</div>

<div id="result" class="card">
<img src="hello.png" class="card_img" alt="result image">
<h4>OFFLINE</h4>
<p>Yes!!</p>
</div>

I am seeking guidance on how to dynamically loop through the contents of this div when a user clicks on a button:

<button id="search" class="btn" value="Search">

I want the contents in this div to be dynamic, negating the need for multiple static divs. How can I achieve this using JavaScript?


EDIT

I am now looking for a way to populate a div with children that match the data from the JSON response below, creating a dynamically loaded list:

[{
    "name": "Malkov Chicken",
    "location": "New York",
    "meals": 5,
    "close_time": 1567289876354
},
{
    "name": "Delicious Chops",
    "location": "San Francisco",
    "meals": 15,
    "close_time": 1567289876354
},
{
    "name": "Banana cultshop",
    "location": "New York",
    "meals": 8,
    "close_time": 1567289876354
}]

The div should populate with data from the JSON list and dynamically create div elements based on the number of responses received from the JSON. For instance, if there are 5 objects in the JSON response, there should be 5 corresponding divs created dynamically.

Answer №1

If you have an array of objects in JSON format, here are the steps you can take:

  • Start by creating a string literal template
  • Utilize the `.map()` method to transform your JSON data into a function called `TPL_Results`
  • Combine the mapped results and insert them into the Document Object Model (DOM)

const restaurants = [{
    "name": "Malkov Chicken",
    "location": "New York",
    "meals": 5,
    "close_time": '23:30'
}, {
    "name": "Delicious Chops",
    "location": "San Francisco",
    "meals": 15,
    "close_time": '22:00'
}, {
    "name": "Banana Cultshop",
    "location": "New York",
    "meals": 8,
    "close_time": '23:00'
}];

const TPL_Results = item => `<div class="Results-item">
  <h3 class="Results-itemName">${item.name}</h3>
  <p class="Results-itemLocation"><b>${item.location}</b></p>
  <p class="Results-itemDetails">Meals: ${item.meals} Close time: ${item.close_time}</p>
</div>`;

document.querySelector("#results")
.innerHTML = restaurants.map(item => TPL_Results(item)).join('');
<div class="Results" id="results"></div>

Answer №2

If you are looking to dynamically add an HTML element on button click, it is important to remember that using a class is preferable over an id since ids must be unique within a document.

You can achieve this by following the example below:

var template = `<div class="result" class="card">
<img src="hello.png" class="card_img" alt="result image">
<h4>OFFLINE</h4>
<p>Yes!!</p>
</div>`;
var occurrences = 3;
document.getElementById('search').addEventListener('click',
function(){
  var strHTML = '';
  for(var i=0; i<occurrences; i++){
    strHTML += template;
  }
  document.getElementById('container').insertAdjacentHTML('beforeend', strHTML);
});
<div id="container"></div>

<button id="search" class="btn" value="Search">Create</button>

Update:

var listArr = [{
    "name": "Malkov Chicken",
    "location": "New york",
    "meals": 5,
    "close_time": 1567289876354
},{
    "name": "Delicious Chops",
    "location": "San francisco",
    "meals": 15,
    "close_time": 1567289876354
},{
    "name": "Banana cultshop",
    "location": "New york",
    "meals": 8,
    "close_time": 1567289876354
}];
document.getElementById('search').addEventListener('click',
function(){
  var strHTML = '';
  listArr.forEach(function(item){
    strHTML += `<div class="Results-item">
            <h4 class="Results-itemName">${item.name}</h4>
            <p class="Results-itemLocation"><b>${item.location}</b></p>
            <p class="Results-itemDetails">Meals: ${item.meals} Close time: ${item.close_time}</p>
            </div>`;
  })
  document.getElementById('container').insertAdjacentHTML('beforeend', strHTML);
});
<div id="container"></div>
<button id="search" class="btn" value="Search">Create</button>

Answer №3

If you want to add multiple cards with the same content, you can create a template for one card in JavaScript and then append several of these cards to a container div.

To add multiple divs with the same content upon button click, generate the string outside of the click event using a for loop, and then append the generated string.

In this example, the container div is named .content. Remember that each element should have a unique ID and IDs should not be repeated.

Check out the working example below:

let card = 
  `<div class="card">
    <img src="https://cdn.sstatic.net/Sites/stackoverflow/img/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2c4d5c5c4049015843594f4401454f43426c1e025c424b">[email protected]</a>?v=73d79a89bded" class="card_img" alt="result image">
    <h4>OFFLINE</h4>
    <p>Yes!!</p>
   </div>`;

let amount = 10; // number of cards to add on button click
let toAppend = '';
for (let i = 0; i < amount; i++) {
  toAppend += card;
}

$("#search").click(function() {
  $('.content').empty().append(toAppend);  
});
img {
  height: 150px;
  width: 150px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="content"></div>
<button id="search" class="btn" value="Search">Click me</button>

In response to your revised question:

You can iterate through your data array using .reduce and build a string containing individual divs using template literals and destructuring. After that, you can append this constructed div to your body or a div (in this case it's appended to a div with the class content).

let data = [{
    "name": "Malkov Chicken",
    "location": "New York",
    "meals": 5,
    "close_time": 1567289876354
  },
  {
    "name": "Delicious Chops",
    "location": "San Francisco",
    "meals": 15,
    "close_time": 1567289876354
  },
  {
    "name": "Banana Cultshop",
    "location": "New York",
    "meals": 8,
    "close_time": 1567289876354
  }
];

let html = data.reduce((acc, {name, location, meals, close_time: close}) =>
      acc += `
      <div class='item'>
        <p>${name}</p>
        <p>${location}</p>
        <p>${meals}</p>
        <p>${close}</p>
      </div>`
, ``);

$('.content').append(html);
.item {
  border: 1px solid black;
  margin: 10px 0;
}
p {
  margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content"></div>

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

There seems to be an issue with updating the ng-model properly in angular-ui-tinymce

I have encountered a problem where I am attempting to add a DOM node when a custom button is clicked, but the model associated with the textarea is not being properly updated. To illustrate the issue, I have created a plunker as a demo. [https://plnkr.co ...

What could be causing my code to fail in the useEffect hook every time I make updates to my JSON

I have a function that receives JSON data from the server. Using the {jsonData.map((element) => renderComponents(element, jsonData))} function, I loop through the data and send each object to the renderComponents function along with the full JSON data. ...

While in Safari, there seems to be a random issue where the embedded image in an SVG becomes blank when using the Canvas API to convert it to

My current approach involves generating a png from a valid svg string that contains an embedded image. The code snippet below illustrates this: <image xlink:href="data:image/png;base64,..." x="0" y="0" width="362" ...

Swap out AJAX following a successful retrieval and when managing errors

I currently have a basic AJAX load function set up to load a specific URL: <div id="load"> <h1 id="status">Loading...</h1> </div> <script type="text/javascript"> $(document).ready(function(){ $.ajaxSetup({cache: false}); var ...

I need guidance on how to successfully upload an image to Firebase storage with the Firebase Admin SDK

While working with Next.js, I encountered an issue when trying to upload an image to Firebase storage. Despite my efforts, I encountered just one error along the way. Initialization of Firebase Admin SDK // firebase.js import * as admin from "firebas ...

Upon rerender, React fails to refresh the style changes

I am encountering an issue with my React component where the visibility and position can be changed by the user. Currently, the visibility can be toggled by adding or removing a CSS class, while the position is adjusted through a function that updates the ...

Why isn't the jQuery colorbox popup appearing when triggered by the $.ajax() function?

I am currently facing an issue where I am trying to display a hidden colorbox popup using the $.ajax() method's success function, but it is not showing up. Interestingly, this had worked fine in a previous implementation where I used the data attribut ...

Angular directive used to create a nested tree list

Currently struggling with a nested list Directive in Angular. Whenever I attempt to run the code, the browser crashes due to the recursive call of the directive. My goal is to display a new list item if the data's children property contains items. H ...

Struggling to Implement Middleware on Router in ExpressJS?

In my application, I have both public and authenticated routes. The isAuthenticated function is used, for example, in a news controller. globalRouter: function (app) { app.use((req, res, next) => { logger.log("Endpoint: ", req.originalUrl); n ...

Node.js Sequelize QueryExplore the power of Sequelize in Node.js

I'm looking to filter the "incomers" based on age, but all I have in the table is their date of birth. I want to find people within a specific age range, how can I accomplish this? router.post('/', function (req, res, next) { let parame ...

Is anyone utilizing PHP variables to control the title of the HTML and the ID of the body element?

I utilize PHP variables to store the title's value and the ID of the body. The latter is a method to show which section of the page the user is currently on (in this case, the "home" section). At the start of my index.php: <?php $title = "New ...

What methods can I use to prevent floated child divs from wrapping?

I'm currently working on creating a carousel-like feature where users can select radio buttons within various div elements. The concept involves having approximately 20 divs, each 150px wide, containing radio buttons. I want to prevent these 20 divs f ...

I recently realized that my website has a strong Björk influence when viewed in IE. Any suggestions for what I should do next

After using Chrome and Firefox for a while, I decided to test out my website on IE8. To my surprise, the results were disastrous. The navigation was impossible, rotations were not rendering correctly, and everything looked like a complete mess. Do any of ...

Enhanced Slider Display featuring Multiple Posts for Improved Performance

My Sample Page features a slider that displays over 200 posts, each containing 5 images. However, the slider loads all the images at once, causing my page speed to be very slow. I am looking for an optimized way to display the slider without compromising l ...

Changing the size of an image in an HTML5 canvas

I have been attempting to generate a thumbnail image on the client side using Javascript and a canvas element. However, when I reduce the size of the image, it appears distorted. It seems as though the resizing is being done with 'Nearest Neighbor&apo ...

Show data in a popup using jQuery DataTables and loading content asynchronously via Ajax

I am attempting to display a list in a popup based on an Ajax request. Prior to the Ajax call, the list is contained within the popup. However, after the Ajax request, the list remains on the page instead of inside the popup, and the old list still appears ...

Utilizing Omit for the exclusion of nested properties within a TypeScript interface

One of the components in a library I am using is defined like this: export interface LogoBoxProps { img: React.ReactElement<HTMLImageElement>, srText?: string, href?: LinkProps['href'] } export type LogoBoxType = React.FC<React.HT ...

What is the best way to implement momentJS globally in VueJS 2?

Currently working with Vue.js version 2.6.11 Trying to set up in main.js as follows: import moment from 'moment' moment.locale('nl'); Object.definePrototype(Vue.prototype, '$moment', { value: moment }); Encountering an error ...

Can someone help me extract a specific portion and display the dimensions of the area?

In order for the mouse to create a selection range, simply release the mouse after making your selection. The selected area will display the values of width and height on both the X-axis and Y-axis in the designated fields. I am facing this issue and woul ...

To avoid any sudden movements on the page when adding elements to the DOM using jQuery, is there a way to prevent the page from

I have a challenge where I am moving a DIV from a hidden iFrame to the top of a page using jQuery. Here is my current code: $(document).ready(function($) { $('#precontainer').clone().insertBefore(parent.document.querySelectorAll(".maincontainer" ...