0

Can anyone tell me why this code for displaying document.getElementById("ibody").innerHTML=... is not working?

<script type="text/javascript">
    var v=new Date();
    document.write("Avec document.write() = "+v);
    window.alert("Avec window.alert() = "+v);
    alert("Avec alert() = "+v);
    console.log("Avec console.log = "+v);
    document.getElementById("ibody").innerHTML=
        "Avec getElementById() ds DIV = "+v
</script>

<body id="ibody"></body>
Phylogenesis
  • 7,775
  • 19
  • 27

2 Answers2

0

Because at the point you are running the code, the <body> element does not exist.

Try wrapping the code block in an event handler that runs once the DOM finishes loading:

<script type="text/javascript">
    document.addEventListener(
        'DOMContentLoaded',
        function () {
            var v=new Date();
            document.write("Avec document.write() = "+v);
            window.alert("Avec window.alert() = "+v);
            alert("Avec alert() = "+v);
            console.log("Avec console.log = "+v);
            document.getElementById("ibody").innerHTML=
                "Avec getElementById() ds DIV = "+v
        }
    );
</script>
Mr Lister
  • 45,515
  • 15
  • 108
  • 150
Phylogenesis
  • 7,775
  • 19
  • 27
0

keep the javascript code under the body decleared

Anupam Biswas
  • 66
  • 1
  • 4
  • – Anupam Biswas Dec 29 '17 at 13:11
  • ` – Phylogenesis Dec 29 '17 at 13:15
  • you can keep the at the bottom of the page as well. and this the best practice to keep the js code at the bottom of the page, and – Anupam Biswas Dec 29 '17 at 13:33
  • Of course they're invalid. As per my link above, the only elements allowed inside `` are a single `` followed by a single `` (see Permitted content). – Phylogenesis Dec 29 '17 at 14:27
  • The link you have shared , that code is absolutely ok, If you declare a function for any event like click etc, then you can keep the function inside the head or anywhere else . But your piece of code has no event , so when it interpreted then the body is not yet interpreted , this is why throwing error, so I am suggesting to keep the js code at lest after the body element , because body need to render first then js code need to executed. – Anupam Biswas Dec 29 '17 at 17:52