Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript innerhtml not working on div

<!DOCTYPE html>
<html>

<head>
    <script>
        document.getElementById("passage").innerHTML = "Paragraph changed!";
    </script>
</head>

<body>

    <div id="passage">hello</div>
    <div id="question"></div>
    <div id="answers"></div>

</body>

</html>

Why is document.getElementById("passage").innerHTML = "Paragraph changed!" not working for me? I just end up with a blank screen, not even the original "hello".

like image 770
GT. Avatar asked Jul 02 '17 13:07

GT.


3 Answers

Your script is called before the element is loaded, try calling the script after loading element

<!DOCTYPE html>
<html>
   <head>
   </head>
   <body>
      <div id="passage">hello</div>
      <div id="question"></div>
      <div id="answers"></div>
      <script>
         document.getElementById("passage").innerHTML = "Paragraph changed!";
      </script>
   </body>
</html>
like image 66
Srinivas ML Avatar answered Sep 30 '22 23:09

Srinivas ML


If you check the console, you can see an error

Uncaught TypeError: Cannot set property 'innerHTML' of null

That is the HTML page is parsed and executed top down.

So, it can't identify what is the element you are mentioning.

So, you should either use an EventListener or place the script just before the end of body tag

Method 1 Event Listener

<!DOCTYPE html>
<html>
<head>
</head>
<script>
window.onload=function(){
  document.getElementById("passage").innerHTML = "Paragraph changed!";
};
</script>
<body>

<div id = "passage">hello</div>
<div id = "question"></div>
<div id = "answers"></div>

</body>
</html>

Method 2 : script is just above body tag

<!DOCTYPE html>
<html>
<head>
</head>

<body>

<div id = "passage">hello</div>
<div id = "question"></div>
<div id = "answers"></div>
<script>
document.getElementById("passage").innerHTML = "Paragraph changed!";
</script>
</body>
</html>
like image 20
Sagar V Avatar answered Sep 30 '22 22:09

Sagar V


You script should be executed once the page is loaded.
Otherwise all elements of the page may not be still attached to the dom when you refer to them.

Rather than moving the script after the element declaration that may be error prone (you should always be aware of the order of script), you could use event designed to be executed after the dom is totally loaded.
For example onload attribute of body :

<body onload='document.getElementById("passage").innerHTML = "Paragraph changed!";'>
like image 29
davidxxx Avatar answered Sep 30 '22 22:09

davidxxx