A guide on using JSON data fetched with Javascript to apply CSS styling

I'm currently working on an HTML document with dynamic content that needs to adjust its styling based on data from Google Sheets. I've successfully loaded the JSON data, but I'm struggling to figure out how to dynamically change the CSS. Can anyone provide guidance on how to achieve this?

<!doctype html>
<html lang="en>

<head>
  <meta charset="utf-8">
  <title>Google Sheets</title>
  <style>
  </style>
  <script type="text/javascript">
    var ourRequest = new XMLHttpRequest();
    ourRequest.open('GET', 'https://spreadsheets.google.com/feeds/cells/1d3z-eJz2X_rFhq3a1kQ6TRlxJqHvstLQ/1/public/full?alt=json')
    ourRequest.onload = function () {
      var ourData = JSON.parse(ourRequest.responseText);
      var adText = ourData.feed.entry[6].gs$cell.inputValue;
      var backgroundColor = ourData.feed.entry[7].gs$cell.inputValue;
      var textColor = ourData.feed.entry[8].gs$cell.inputValue;

      console.log(adText);
      console.log(backgroundColor);
      console.log(textColor);

      document.getElementById('testoutput').innerHTML = adText + " " + backgroundColor + " " + textColor;
    };

    ourRequest.send();

  </script>
</head>

<body>
  <div id="testoutput"></div>
</body>

</html>

Answer №1

To achieve this, you can utilize javascript to toggle classes.

document.getElementById('output').classList.toggle('activeClass');

Alternatively, you can modify specific CSS properties directly.

document.getElementById('output').style.color = 'blue';

Answer №2

Absolutely, you have the ability to apply specific CSS styles to each column by using HTML tags. Check out the code snippet below for an example:

<!doctype html>
<html lang="en>

<head>
    <meta charset="utf-8">
    <title>Google Sheets</title>

<style>

</style>


<script type="text/javascript">
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'https://spreadsheets.google.com/feeds/cells/1dLbBxSuyGxbG3z-eJz2X_rFhq3a1kQ6TRlxJqHvstLQ/1/public/full?alt=json')
ourRequest.onload = function() {
var ourData = JSON.parse(ourRequest.responseText);
var adTekst = ourData.feed.entry[6].gs$cell.inputValue;
var achtergrondKleur = ourData.feed.entry[7].gs$cell.inputValue;
var tekstKleur = ourData.feed.entry[8].gs$cell.inputValue;

console.log(adTekst);
console.log(achtergrondKleur);
console.log(tekstKleur);

document.getElementById('testoutput').innerHTML ='<span>'+adTekst+'</span>'+ " " + '<span>'+achtergrondKleur+'</span>' + " " + tekstKleur;
};

ourRequest.send();

</script>
</head>

<style>
div#testoutput {    color: red;}
div#testoutput span {    color: blue;}
div#testoutput span:first-child {color: aqua;}
</style>
<body>

<div id="testoutput"></div>

</body>
</html>

You have the flexibility to customize the color and design to meet your specific needs.

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

What is the best approach for generating a JSON object programmatically?

I want to dynamically create a JSON object. The structure of the JSON object needs to be like this: { $capa:[$fila['test_name'],...etc], . . .etc }; The key and value will co ...

MUI version 5 - Checkboxes are receiving a variety of unique classes

After recently upgrading from Mui v4 to v5, I've noticed a strange behavior with checkboxes. Upon inspecting the DOM differences between the two versions, it appears that some additional classes are now being applied in v5 and the extra span with the ...

How can I implement Google Analytics Event tracking for all <audio> tags using Javascript?

I am looking to implement a Google Analytics Event for all audio tags on my website. Currently, I have a script that targets audio tags with a specific class: <script> /* a test script */ $(function() { // Execute function when any element with t ...

Using mix-blend-mode with an SVG image within a colored <div>: tips for applying it to the background color of your HTML

I am facing an issue with a SVG file that has mix-blend-mode styles defined on certain elements. The blending is working properly for the elements inside the SVG, but not for the background color of the HTML <div>. For instance: <!doctype html> ...

Tips for serving images locally instead of using an online URL when exporting with Next.js static:

I've encountered an issue where multiple images pulled from an online source are not being included in my export when I start the process. The image URLs are stored as strings online, but I want them to be saved locally and exported that way instead o ...

Issues with displaying or hiding a DIV using javascript - popup box unresponsive

I am working with this ASPX code: <div id="IsAccountingOk" class="modalDialog"> <div> <a href="#close" title="Close" class="close">X</a><br /> <asp:Label ID="lblIsAccountingOkHeader" runat="server" Text ...

What is the best way to track the loading progress of an AJAX page in WordPress?

On my WordPress blog, I utilize a plugin known as Advanced Ajax Page Loader. This handy tool loads the next page or post through AJAX and then places it in a specific div on my site. However, I am now interested in incorporating a progress bar to show the ...

employing the d3.queue method to defer execution until receiving the AJAX response

Seeking examples of integrating AJAX, d3, and PHP to extract data from a database and create graphs. Any guidance would be appreciated. I am currently using d3 to generate a force chart based on database information retrieved through AJAX and PHP. I have ...

The dynamic loading of select tag options in Vue.js is not rendering properly

I'm having trouble displaying a select tag with options loaded from a Vue object. However, when I try to render it, something seems off: https://i.sstatic.net/odbC6.png Here is the HTML markup for the select tag: <div class="form-group ui-model" ...

"Using Node.js Express 4.4 to efficiently upload files and store them in a dynamically

Looking for recommendations on the most efficient method to upload a file in node.js using express 4.4.1 and save it to a dynamically created directory? For example, like this: /uploads/john/image.png, uploads/mike/2.png ...

What is the best way to eliminate YouTube recommended videos that appear at the conclusion of my video?

I am attempting to incorporate my own YouTube video onto my blog without having recommended videos display at the end. I have tried using ?rel=0 and &rel=0 but they do not seem to be working. <iframe class="embed-responsive-item" src="https://www.y ...

How to Use AFNetworking to Parse JSON on iOS and Fetch Targeted Data?

I am currently utilizing AFNetworking's AFHTTPRequestOperationManager to make a call to the wunderground API in this manner: AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; [manager GET:urlString parameters:nil succe ...

The elements within the HTML, CSS, and Bootstrap are all clashing and

Website Output https://i.sstatic.net/5JVyg.jpg I've been working on a small website with a bootstrap carousel, and in this specific section of the program, the Bootstrap and HTML/CSS elements overlap by default. I'm not sure how to separate the ...

A few of the input fields I filled out are not getting sent to the PHP script

Currently, I am working on a school project that involves creating a website similar to IMDB. My task is to include comments in our database, but I am facing an issue where two fields (fid and spoiler) are not getting posted to the PHP script handling the ...

What steps can I take to stop my Details element from moving a nearby Div?

Within this setup, there is a div containing Details and Summaries to the left. Upon expanding the details, the text enlarges and the container moves, causing the image in the right div to shift downward. Is there a way to prevent this from happening? I ...

Sending users to a different page in case the linked document from <a> cannot be located

I am in search of a way to set up an alternative link for a hyperlink in case the primary link does not exist, similar to how 'alt' works for images. I am aware of the existence of 'onerror' but it doesn't work for HTML links. I wo ...

Can one create a set of rest arguments in TypeScript?

Looking for some guidance on working with rest parameters in a constructor. Specifically, I have a scenario where the rest parameter should consist of keys from an object, and I want to ensure that when calling the constructor, only unique keys are passed. ...

Synchronizing client information in real-time: tips, tricks, and expert advice

Currently, I am developing a PHP backend and utilizing JS/Jquery for the front end of an application that aims to facilitate near real-time communication among users. My main concern right now is determining the most effective approach to achieve this goal ...

Generating distinctive content within the confines of the Selenium WebDriver

Is there a way to generate a unique username value for the signup page username textbox using selenium webdriver instead of hardcoding it? For example: driver.findElement(By.id("username")).sendKeys("Pinklin") ; When "Pinklin" is hardcoded, running the ...

Tips for searching my JSON document for a particular key

Currently working on a project that involves querying a JSON file using jQuery, but encountering an error: jq: error: syntax error, unexpected IDENT, expecting $end (Unix shell quoting issues?) at <top-level>, line 1: ..id jq: 1 compile error Error ...