0

I have created the one function to calculate the Body Mass Index. I want to show the result on web. But, I am getting one error that Cannot set property 'innerHTML' of null? Below, I am sharing the code:

JS Code here:

function calBodyMass() {
    var addHeight = document.getElementById("mass").value;
    var addMass = document.getElementById("height").value;
    var calculateBodyMass = addMass /(addHeight * addHeight);
    console.log(calculateBodyMass);
    document.getElementById("showResult").innerHTML = calculateBodyMass; 
}

HTML Code Here:

<div>
  <div class="add-mass">
    <label class="inputLable">Add Wieght</label>
    <br />
    <input type="text" value="" id="mass" />
  </div>
  <br /><br />
  </div class="add-height">
    <label class="inputLable">Add Height</label>
    <br />
    <input type="text" value="" id="height" />
  </div>
  <br /><br />
  <button onclick="calBodyMass()">calculate</button>
  <br /><br />
  <span id="showResult"></span>
</div>

function calBodyMass() {
    var addHeight = document.getElementById("mass").value;
    var addMass = document.getElementById("height").value;
    var calculateBodyMass = addMass /(addHeight * addHeight);
    console.log(calculateBodyMass);
    document.getElementById("showResult").innerHTML = calculateBodyMass; 
}
<div>
  <div class="add-mass">
    <label class="inputLable">Add Wieght</label>
    <br />
    <input type="text" value="" id="mass" />
  </div>
  <br /><br />
  </div class="add-height">
    <label class="inputLable">Add Height</label>
    <br />
    <input type="text" value="" id="height" />
  </div>
  <br /><br />
  <button onclick="calBodyMass()">calculate</button>
  <br /><br />
  <span id="showResult"></span>
</div>
JGFMK
  • 7,107
  • 4
  • 46
  • 80
  • 1
    Then `document.getElementById("showResult")` doesn't return the element you think it does. *Always* suspect your selectors. If you're confident there really is an element in the DOM with that ID, it may be you're running this code before the DOM has loaded. – Mitya Dec 29 '19 at 12:40
  • You must have a typo in an id, (specifically showResult) since the code you entered works. I edited the question and inserted it more or less verbatim, and it works as you have typed it. And you have a typo - for Weight! ;-) You also should check for divide by zero error too! – JGFMK Dec 29 '19 at 12:47

1 Answers1

1

I found it's working fine for me. You can check this link

Btw there was a typo in one of your starting div You've misspelled the starting <div> with a </div> (Though that may not be the reason)

Sifat Haque
  • 3,137
  • 1
  • 11
  • 19