0

I am learning HTML/Javascript, and am writing some simple functions. I used console.log to return an element, and it returned fine, however, in the same function, when I try to use getElementById(), then I received an error in the console which says that the value is null. Could you help me understand what is wrong?

function calculateProfict() {
   var consumoW_H = 2960;
   var consumoW_D = 2960 * 24 * 0.001; 
   var prezzoElettricita = 0.22;
   var consumoElettricita_D = consumoW_D * prezzoElettricita;
   var valore_BTC = 12.5;
   var valore_BTC_D = 144 * valore_BTC;
   var hashrateGlobal = 100000000
   var networkHashratePercentage = document.getElementById("networkHashrate").innerHTML/hashrateGlobal;
   var BTC_D = networkHashratePercentage * valore_BTC_D;
   var euroBTC_D = BTC_D * 6471.90;
   var guadagno = euroBTC_D - consumoElettricita_D;
   console.log(guadagno) //Return -15.62
   document.getElementById("guadagno").innerHTML = guadagno; //null is not an object

}

I also tried with .value (I don't know if it's right or not) but I received the same error. My point is why I can use console.log and not document.getElementById? Thanks guys and happy new year

JΛYDΞV
  • 8,532
  • 3
  • 51
  • 77
  • This is javascript code. Could you show your HTML? It is likely that you haven't set an id to the element you are trying to find with `.getElementById()` – PajLe Jan 01 '20 at 16:36
  • 3
    That `null` means that you don't have any element with `id="guadagno"` when you invoke `calculateProfict()`. What I don't really understand is why you expect `console.log(guadagno)` to have anything to do with that. – Álvaro González Jan 01 '20 at 16:37
  • @Pajacar123 this is the HTML code. I made the function in the page. I know it's not a right implementation. I should make logic in a different page. – Chicca641994 Jan 01 '20 at 16:40
  • @ÁlvaroGonzález the console.log is just to be sure that the value exists. I will try to add an element with id="guadagno" to be sure it will work – Chicca641994 Jan 01 '20 at 16:41
  • 1
    @ÁlvaroGonzález thanks it works fine. If you put your comment as answer I will set as the correct one. I'm sorry if the question was stupid. I'm still learning – Chicca641994 Jan 01 '20 at 16:43
  • 1
    `var guadagno` is just a JavaScript variable name. It doesn't anything to do with HTML IDs. – Álvaro González Jan 01 '20 at 16:43
  • @ÁlvaroGonzález Yes absolutely. I will divide my work with a .js file to have a good code – Chicca641994 Jan 01 '20 at 16:45

0 Answers0