I am calling data from Google Sheets using IDs and am using document.querySelectorAll to add a positive or negative class to positive or negative numbers. Currently this is applied to #Title and #Title2. But I'd like to be able to select different IDs and do something else to them. So I'd like #Title3 to be positive if it is equal to '2' for example and not apply the styling that #Title and #Title 2 have. I basically want to create multiple query selectors.

I have managed to do this but by basically making two separate requests to the Google Sheet but it is slow and surely there's a better way? https://codepen.io/liamdthompson/pen/xNrBML?editors=1010

  function httpGetAsync(theUrl, callback)  {

  var xmlHttp = new XMLHttpRequest();
  xmlHttp.onreadystatechange = function() {
  if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
      callback(xmlHttp.responseText);
  }
  xmlHttp.open("GET", theUrl, true); // true for asynchronous
  xmlHttp.send(null);

  }


  httpGetAsync ('https://spreadsheet.glitch.me/?key=1mT_ILqpPtoCnWq5fEcBbVcgkKxcXN6uS9F2fsAO7imI', function(response) {
  var json = JSON.parse(response);

  document.getElementById("Title").innerHTML = json[0].Title;
  document.getElementById("Title2").innerHTML = json[1].Title2;
  document.getElementById("Title3").innerHTML = json[2].Title3;

let divs = Array.prototype.slice.call(document.querySelectorAll("#Title, #Title2"));

  // Loop the array
    divs.forEach(function(div){
        // Convert text to number and test for positive/negative
        if((+div.textContent) >= 0){
        div.classList.add("positive"); // Apply positive style
        } else {
        div.classList.add("negative"); // Apply negative style  
        }
    });  
    });

0 Answers