0

I am doing a really simple task. I am adding some javascript code in html of a simple web project created on Visual studio 2019. But it is not running the code inside a script tag and also not giving any error. I know it's gonna be really small mistake that i am unable to figure out right now. Please help.

<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <h1>JS Code</h1>
    <button type="button"
            onclick="document.getElementById('demo').innerHTML = Date()">
        Click me to display Date and Time.
    </button>

    <script type="text/javascript">
        var x = "John Doe";  // String written inside quotes
        document.getElementById("demo1").innerHTML = x;
    </script>

    <p id="demo"></p>
    <p id="demo1"></p>

</body>
</html>

After running a code, code within button tag is working fine but script isn't working. Sorry for a really stupid question. I will highly appreciate your help

Faizan Kamal
  • 1,732
  • 3
  • 27
  • 56

1 Answers1

4

Your script tag is added before <p id="demo1"></p> which you reference in your script. So when the script runs there is no such tag and "John Doe" can't be added to it. Fixed:

<html>
<head>
    <meta charset="utf-8" />
    <script></script>
    <title></title>
</head>
<body>
    <h1>JS Code</h1>
    <button type="button"
            onclick="document.getElementById('demo').innerHTML = Date()">
        Click me to display Date and Time.
    </button>

    

    <p id="demo"></p>
    <p id="demo1"></p>
    <script type="text/javascript">
        var x = "John Doe";  // String written inside quotes
        document.getElementById("demo1").innerHTML = x;
    </script>
</body>
</html>
Mohrn
  • 816
  • 4
  • 15