-1

i think that the code 100% normal but why i got that Error????: Uncaught TypeError: Cannot set property 'innerHTML' of null||

the code is:

<!DoCTYPE html>
<html lang="eng">
<head>
    <meta charset ="utf-8">
    <meta name="" content="">
    <title></title>
    <script>
        function myAgeInDays() {
        
        "use strict";
        
        var myAge = 15;
        
        return myAge * 365;
    
    }
    
    var daysCalc = myAgeInDays();
    
    document.getElementById("test").innerHTML =
    
        "Your Age In Days = "+ daysCalc+ " Day";
    </script>
</head>

<body>
    <button onclick="myinfo();">OK</button>
    <h1 id="test">Ok</h1>
</body>
    
</html>
Yousof
  • 9
  • 3

1 Answers1

2

A few things can be done to improve this question:

Give some context, not the error the console prints out

Especially in the case of a very common js error. An example for your case could be "In form submission cannot select html element / selector is null in onclick function".

State some of the things you have tried

This will help you grow as a developer (the old teaching someone to fish story)

Some more tips here: https://stackoverflow.com/help/how-to-ask

In your case, the code you posted does not work (myinfo is not defined) and your code is in the <head> which is defined before the <p> is created. add it at the end of your body to ensure that all the elements are created. If you wanted to make a function handle the button click that contained the logic in your , you would write something like:

<body>
  <button id="calcDays">OK</button>
  <h1 id="test">Ok</h1>
  <script type="text/javascript">
    document.getElementById('calcDays')
      .addEventListener('click', function () {
          function myAgeInDays(days) {
            return days * 365;
          }

          document.getElementById("test").textContent =
            `Your Age In Days = ${myAgeInDays(15)} Days`;
      });
  </script>
</body>
connexo
  • 41,035
  • 12
  • 60
  • 87