0

I'm trying to create a button that you click on and it will do the calculations for the user's age and my JavaScript code will write the user's age on the document itself using innerHTML. I don't understand why it's not working. I'm getting no response not even an error.

Here's my JavaScript:

let btn = document.getElementById("btn");

  btn.addEventListener('click',howOldAreYou)

  function howOldAreYou(){

  let age= document.getElementById("year").value
  let currentYear = 2021
  
  let howOld= currentYear - age;

  document.innerHTML= howOld;

}
isherwood
  • 58,414
  • 16
  • 114
  • 157
  • [Documents](//developer.mozilla.org/en-US/docs/Web/API/Document) don’t have an `innerHTML` property. Creating one is meaningless. – Sebastian Simon Jun 16 '21 at 13:44
  • 1
    [Duplicate](//google.com/search?q=site%3Astackoverflow.com+js+%22document.innerHTML%22+not+working) of [javascript document.innerHTML set content of whole document](/q/6758081/4642212). – Sebastian Simon Jun 16 '21 at 13:47

2 Answers2

1

You are looking for document.body.innerHTML or document.documentElement.innerHTML.

document is not an element, and thus does not have the innerHTML property.

Spectric
  • 30,714
  • 6
  • 20
  • 43
  • @carringtonCodes If it helped, please consider accepting! :) [How do I accept an answer?](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) – Spectric Jun 16 '21 at 14:03
1

I think the problem is that you are not using the innerHTML element property correctly, it should be yourElementId.innerHTML instead of document.innerHTML

Try this:

btn.addEventListener('click',function(){
  let age = document.getElementById("year").value;
  let currentYear = 2021;
  let howOld = currentYear - age;
  result.innerHTML = howOld;
});
<button id="btn">Calculate</button>
<input id="year"/>
<div id="result"></div>
Gass
  • 7,536
  • 3
  • 37
  • 41