sina sina - 1 month ago 13
Javascript Question

hi why this simple snippet code doesnt work?im confused

i want to show the paragraph in div



var resultString = "<b>This page \u00A9 Shelley Powers </b>";
// print out to page
var blk = document.getElementById("result");
blk.innerHTML = resultString;

<div id="result"></div>




Answer

The problem could be related to the position of your JS code in your HTML file.

If you add that code, after body tag, it will work because JS can find a reference of your dom <div id="result"></div>.

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

If instead you add that javascript at the HEAD of your HTML file,

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

    </html>

You need to wait until the document is ready using DOMContentLoaded.

document.addEventListener("DOMContentLoaded", function(event) {
    console.log("DOM fully loaded and parsed");
  });

Working example:

https://jsbin.com/nerarul/edit?html,output