0

I am trying to run a program but when I put the javascript getElementById method in header section then the code is not executed but when I put it in body section below my html then it gets executed. Please tell me the reason

<html>
<head>
    <script type="text/javascript">
        document.getElementById("addition").innerHTML= 5+6;

    </script>
</head>
<body>
<span id="demo"> 5+6 =</span><span id="addition"></span>

  • 1
    Can you say what is "sdfdsfdsfds90"? Most likely you can't, not before I'll tell you what it is ... The same stands for JS, you're trying to refer an element which is not created yet, when the script is in `head` as it is now. – Teemu Nov 11 '19 at 06:01
  • What will happen if i put the same code in external file and link the file in header section – shubham agrawal Nov 11 '19 at 06:04
  • The same error occurs. The `head` element is guaranteed to be parsed, and the scripts in it are guaranteed to be executed before parsing the body is started, that's why it is "head". You can add an external script to the head with defer or async attribute, then the execution is delayed to the time `body` will be ready. – Teemu Nov 11 '19 at 06:06

1 Answers1

0

When you add a Javascript code in the header, it runs before the body. So, in that moment, there is no element with id "addition" yet.

To keep that simple, you should add your script in the bottom of your tag.

<html>
<head>
<title>Hello World</title>
</head>
<body>
<span id="demo"> 5+6 =</span><span id="addition"></span>
    <script type="text/javascript">
        document.getElementById("addition").innerHTML= 5+6;

    </script>
</body></html>

Another option is putting your code in a function and calling that function into the onLoad attribute on the body tag.

    <html>
    <head>
    <title>Hello World</title>
        <script type="text/javascript">
          function letsDoIt(){
            document.getElementById("addition").innerHTML= 5+6;
          }
        </script>
    </head>
    <body onload="letsDoIt()">
    <span id="demo"> 5+6 =</span><span id="addition"></span>
    </body></html>

More info about events order can be found here https://javascript.info/onload-ondomcontentloaded.

Thiago Mata
  • 2,262
  • 28
  • 27
  • Thankyou for your valuable answer!! – shubham agrawal Nov 11 '19 at 06:23
  • If an answer like this is likely to be already asked and answered multiple times, then you should consider finding a good duplicate instead of writing just another answer for it. If you think that your answer has some additional important information missing in the answers of the duplicate then you should consider writing an answer form the duplicate. – t.niese Nov 11 '19 at 06:33