GT.
GT.

Reputation: 792

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".

Upvotes: 5

Views: 21132

Answers (4)

techhunter
techhunter

Reputation: 693

Your script is calling before element is loaded.

Try

$(document).ready(function()
{
    document.getElementById("passage").innerHTML = "Paragraph changed!";
});

JS:

(function(){
    document.getElementById("passage").innerHTML = "Paragraph changed!";
})

Upvotes: 0

Srinivas ML
Srinivas ML

Reputation: 730

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>

Upvotes: 8

davidxxx
davidxxx

Reputation: 131346

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!";'>

Upvotes: 1

Sagar V
Sagar V

Reputation: 12478

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>

Upvotes: 4

Related Questions