Tips for using JavaScript to style an array items individually

I have currently placed the entire array within a single div, but I would like to be able to display each element of the array separately so that I can style "date", "title", and "text" individually.

This is my JSON structure:

[
 {
     "date": "Example Date",
     "title": "Example Title",
     "text": "Example Text" 
 },
 {
     "date": "Example Date",
     "title": "Example Title",
     "text": "Example Text"
 },
 {
     "date": ""Example Date",
     "title": "Example Title",
     "text": "Example Text"
 }
 ]
 

This is my HTML setup:

<div id="myData"></div>
 

Using Fetch API:


         fetch('example.json')
         .then(function (response) {
             return response.json();
         })
         .then(function (data) {
             appendData(data);
         })
         .catch(function (err) {
             console.log('error: ' + err);
         });

     function appendData(data) {
         var mainContainer = document.getElementById("myData");
         for (var i = 0; i < data.length; i++) {
             var div = document.createElement("div");
             div.innerHTML = data[i].date + data[i].title + data[i].text;
             mainContainer.appendChild(div);
         }
     }
 

Is there a way to create 3 separate divs instead of one, with each individual div displaying the "date", "title", or "text" elements for styling purposes, instead of having all 3 items within one div?

I attempted to use 3 functions to segregate "date", "title", and "text", but it only displays the last item in the array, which is typically the "text" information. Keep in mind that I am new to JavaScript.

Answer №1

Update the line of code containing innerHTML with:

div.innerHTML = '<span class="date">' + data[i].date + '</span>' + 
                '<span class="title">' + data[i].title + '</span>' +
                '<span class="text">' + data[i].text + '</span>' ;

You can style the date, title, and text elements using CSS classes.

Check out a live example on CodePen

Answer №2

Why not create 3 divs for each array element instead of just one?

fetch('example.json')
  .then(response => response.json())
  .then(appendData)
  .catch(console.error)

function appendData(data) {
  const mainContainer = document.getElementById("myData");
  for (const {date, title, text} of data) {
    const div = document.createElement("div")
    div.append(
      textDiv(date, 'date'),
      textDiv(title, 'title'),
      textDiv(text, 'class')
    )
    mainContainer.append(div)
  }
}

function textDiv(text, cls) {
  const div = document.createElement("div")
  div.textContent = text
  if (cls) div.className = cls
  return div
}

Answer №3

One way to loop through the properties of an inner object is by using the for-in method. This allows you to iterate over the keys dynamically without needing prior knowledge of what keys to expect.

fetch("https://api.myjson.com/bins/r9hhx")
  .then(function(response) {
    return response.json();
  })
  .then(function(data) {
    appendData(data);
  })
  .catch(function(err) {
    console.log("error: " + err);
  });

function appendData(data) {
  var mainContainer = document.getElementById("myData");

  for (var i = 0; i < data.length; i++) {
    const item = data[i];
    var outerDiv = document.createElement("div");
    outerDiv.className = `item outer`;

    for (var key in item) {
      var innerDiv = document.createElement("div");
      innerDiv.innerHTML = item[key];
      innerDiv.className = `item inner ${key}`;
      outerDiv.appendChild(innerDiv);
    }
    mainContainer.appendChild(outerDiv);
  }
}
body {
  font-family: sans-serif;
}

.item {
  padding: 10px;
  border: 1px solid #ccc;
}

.date {
  background: rgba(0, 121, 0, 0.1);
}

.title {
  background: rgba(255, 0, 0, 0.1);
}

.text {
  background: rgba(0, 0, 255, 0.1);
}
<div id="myData"></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

Automatic popup updates when submitting a form in a Chrome extension

Looking to develop a chrome extension popup window that, when clicked, will present a form for users to input their name and college. The goal is to save this data in chrome storage and then replace the popup with a new window displaying a greeting message ...

What could be causing my jQuery handler to not capture my form submission?

I am developing a Ruby web application and using JQuery and AJAX to send/receive data. However, I am facing an issue where pressing the enter key does not submit the form. What should I do to ensure that my form submits successfully? Within my Foundation ...

showcasing products from database with the help of Angular 12

Here are the files related to the item: Item file And here is the component file: Component file Lastly, this is the data service file: Data Service file However, issues arise when testing the code with console log statements as it indicates that the ...

Using ajax for transferring form data to a different php page

Hello everyone, I'm in need of assistance. I have a form on one PHP page and I want to use AJAX to pass the data to another PHP page that will update my database and then return the results. <form name="profile" class="profile"> < ...

Begin using datatables with the xp:table component

Within an XPage, there is a table component: <xp:table id="tblProposals"> I am looking to apply the datatables plugin to this table using a scriptblock component: <xp:scriptBlock id="scriptInitProposals"> < ...

Adjust size of element in relation to Background Cover using jQuery

Can you help me solve a challenge I'm facing? I have a website with a fullsize background image, and I need to attach a div to a specific position on the image while ensuring that it scales in the same way as the background image with the "background ...

Vanishing Act: React-js MUI Tooltip vanishes upon clicking

The standard behavior of the MUI Tooltip is as follows:
 If the button/icon to trigger a tooltip is not in focus, the tooltip will not disappear when clicking directly on the popper. However, if the button/icon is focused, the tooltip will disappear upo ...

What is the reason for DialogContent displaying a scroll bar instead of expanding further when nested Grids with spacing are included?

My current project involves working on a form displayed in a dialog window. To adjust the layout of the form's fields, I utilize multiple Grid elements nested within another Grid. However, I've encountered an issue where adding any spacing to the ...

Entering numbers using <input type="number"> does not restrict invalid inputs, while accessing "element.value" does not give me the ability to make corrections

According to the MDN documentation on the topic of <input type="number">: It is said that they have built-in validation to reject entries that are not numerical. But does this mean it will only reject non-numerical inputs when trying to ...

Tips for Passing On Parent tabindex Value to Children

Is there a way to propagate a parent's tabindex value to all of its children without individually setting tabindex for each child? Here is an example code snippet: <div id="app"> <div tabindex="2" class="parent-sec ...

The option to "open in new tab" is absent from the right-click menu when clicking a link on a website

Why does the option to open a link in a new tab not appear when using JavaScript or jQuery, but it works with an anchor tag? I have tried using window.location and window.open, as well as adding the onclick attribute to a div, but the option still doesn&ap ...

"Experiencing issues with Mongoimport when using JSON files - the provided JSON file seems

My attempt to import JSON data into MongoDB via a JSON file using the command below is resulting in an error: mongoimport --db my_db --collection m_data --type json --file /home/uname/email_my.json -v One of my key values contains a complete HTML with sp ...

Tips for getting flex-end to function properly in IE11

My attempt to implement justify-content: flex-end; for a DIV with hidden overflow content in IE11 was unsuccessful. Despite trying various approaches, I managed to create a basic code snippet that functions properly in Chrome but fails in IE11: .token- ...

Use jQuery to smoothly scroll a div

I created a container using a <div> element which is divided into 3 inner divs. The first two inner divs are meant to serve as previous and next buttons, with ids of prev and next respectively. At the bottom, there are 3 more inner divs, each with un ...

PHP's json_encode() compared to using an empty NSDictionary in iOS development

I have a question regarding how to handle JSON encoding/decoding in PHP without converting arrays or dictionaries. In my iOS app, I store data in an NSDictionary. Some of this data is nested and includes NSArrays or other NSDictionarys that may contain fu ...

Webpack 4.1.1 -> The configuration.module contains a property 'loaders' that is unrecognized

After updating my webpack to version 4.1.1, I encountered an error when trying to run it: The configuration object is invalid. Webpack has been initialized with a configuration that does not match the API schema. - The 'loaders' property in ...

The observable did not trigger the next() callback

I'm currently working on incorporating a global loading indicator that can be utilized throughout the entire application. I have created an injectable service with show and hide functions: import { Injectable } from '@angular/core'; import ...

Unable to display Apexcharts bar chart in Vue.js application

Struggling to incorporate Apexcharts into my Vue.js site, but unfortunately, the chart isn't appearing as expected. -For more guidance on Apexcharts, check out their documentation Here HTML <div class="section sec2"> <div id="chart" ...

Node.JS executes Sandbox within a RESTful service environment

Utilizing the Node Restify Module to develop a REST service that accepts POST requests. Inside the service, I am attempting to create a Sandboxed process using the Node Sandbox module in order to execute dynamically inserted JavaScript without impacting th ...

The importance of managing both synchronous and asynchronous processes in Javascript

As I delved into the intricacies of Javascript's asynchronous behavior within its single-threaded environment, I stumbled upon a comment that caught my attention regarding the following code snippet: request(..., function (error, response, body) ...