简体   繁体   中英

How to set CSS using JSON data retrieved with Javascript

I am working on an dynamic HTML document that has to change its styling based on Google Sheets entries. So far it loads the JSON data just fine. I have been looking for a way to style the CSS so I can change it on the fly. Is there anyone that can point me in the right direction?

<!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 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 = adTekst + " " + achtergrondKleur + " " + tekstKleur;
    };

    ourRequest.send();

  </script>
</head>

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

</html>

You can do that by toggling classes using javascript.

document.getElementById('testoutput').classList.toggle('myClass');

Other way is to change individual CSS properties

 document.getElementById('testoutput').style.backgroundColor = 'RED';

Yes you can, you also give specific css to all columns with using html tags. See snippet below

 <!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 can give color or design as per your requirement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM