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

Obtaining variable content from a JavaScript function

Learning JS with documentation has been a challenging journey for me. The concept of variables inside and outside a function still confuses me. I'm interested in creating a module that allows me to reuse code written in different parts of my program ...

I am attempting to invoke a JavaScript function from within another function, but unfortunately, it does not seem to be functioning

I encountered an issue that is causing me to receive the following error message: TypeError: Cannot read property 'sum' of undefined How can this be resolved? function calculator(firstNumber) { var result = firstNumber; function sum() ...

Transfer information from the ajax success event to an external else/if statement

I am encountering an issue when trying to transfer the appropriate result from my ajax success function to an external function for further use. Currently, I am using user input to query a data source via ajax and receiving the object successfully. The re ...

Customize the label and value in Material UI React Autocomplete

If you visit this link, you can see an example of what I'm trying to achieve. My goal is to have the option label and value be different from each other. In the provided example, the following code snippet is used: const defaultProps = { ...

Every time I receive a message, I find myself inundated with unnecessary information. Is there a way to

I am receiving messages from PubNub, but I am only interested in responses of "Yes" or "No". The messages I'm getting include {u'text':'Yes'} and {u'text':'No'}. How can I filter out the extra information? Belo ...

Navigating smoothly through different URLs to a single state using Angular's UI-Router

I recently started using angular's ui-router and I am looking for a way to configure multiple URLs to point to the same state. For instance: /orgs/12354/overview // should show the same content as /org/overview Currently, my $state provider is set u ...

Breaking down a large JSON array into smaller chunks and spreading them across multiple files using PHP pagination to manage the

Dealing with a large file containing over 45,000 arrays can be challenging, especially on a live server with high traffic. To address this issue, I used the array_chunk($array, 1000) function to divide the arrays into 46 files. Now, my goal is to access a ...

Does JSON.Stringify() change the value of large numbers?

My WCF service operation returns an object with properties of type long and List<string>. When testing the operation in a WCF application, everything functions correctly and the values are accurate. However, when attempting to call the service using ...

Select the even-numbered occurrences of a specific class in CSS using the nth-child()

I am encountering an issue with my table layout. The structure is similar to the following: <tbody> <tr class="row">...</tr> <tr class="row--expanded">...</tr> <tr class="row">...</ ...

Utilizing JavaScript for enhancing the appearance of code within a pre element

Is there a way to dynamically highlight the code inside a pre element using vanilla JavaScript instead of JQuery? I'm looking for a solution that colors each tag-open and tag-close differently, displays tag values in another color, and attributes with ...

Preventing the Sending of Origin Header in Angular 2

I am facing an issue in my Angular2 project where the HTTP service is automatically adding the 'Origin' header with a value to all of the requests. Is there a way to stop Angular2 from including this 'Origin' header in the HTTP calls? A ...

Arrow icon from Material UI for a smaller device

As I work on coding a tab bar, I have encountered an issue where the indicator arrow button () is not displaying when the width of the tab bar goes below 600px. I would like it to appear like this: https://i.stack.imgur.com/PDum9.png However, currently i ...

What is the process for extracting context or span from an incoming http request in NodeJS without relying on automated tools

I am currently in the process of transitioning my Node.js application from using jaeger-client to @opentelemetry/* packages. Within my Node.js application, I have a basic http server and I aim to generate a span for each response. Previously, with jaeger ...

Ways to eliminate text following a string substitution

When running the code below with keys assigned to summer, spring, fall, and winter, the output for ins would be: ['req.body.summer, req.body.spring, req.body.fall, req.body.winter'] I need to eliminate the surrounding string from the replace co ...

Remove hidden data upon moving cursor over table rows after a delay

Hey there! I'm in need of a little assistance, so I hope you can lend me a hand. Here's the scenario: Within my category table, there are numerous rows, each containing a hidden textbox with an empty value and a unique ID. As users navigate t ...

What is the best way to integrate Sass into my CSS?

Currently, I am diving into the world of Sass and I am truly impressed by its simplicity. However, I have encountered a hurdle when it comes to compiling and importing my styles. Whenever I look at my style.css file, I notice that it includes not only the ...

How to showcase images and text from an array of objects using React

I'm currently working on a React lightbox that is supposed to display a loop of objects containing images and text. However, I'm facing an issue where the images are not showing up with the corresponding text label as intended. It seems like I a ...

Tips for addressing the issue of mat-list-item not occupying the entire row's space

Hello everyone, I am currently trying to render an article.component.html within my article-list-component.html in a list format. When I use plain HTML, it renders correctly as shown in picture 1: Title - author - Date Here is the code for my article-list. ...

Struggling to access a JSON file using Angular framework

I'm currently working with the following JSON and controllers: JSON Format: {"tomcatLogDir":"C:\\apache-tomcat-7.0.70\\logs","tomcatLogs":["1.log","2.log","3.log"]} Factory: app.factory('filesFactory', [ '$http&a ...

jQuery form validation issue, unresponsive behavior

<!DOCTYPE html> <html> <head> <title> jquery validation </title> </head> <body> <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js" type="text/javascript"> ...