..."> ...">

Javascript innerhtml not working on div

13,896

Solution 1

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>

Solution 2

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>

Solution 3

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!";'>
Share:
13,896
Author by

GT.

noob "programmer", some would say amateurgrammer

Updated on June 27, 2022

Comments

  • GT. 5 months
    <!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".

  • Drew Kennedy
    Drew Kennedy over 5 years
    You're better off just putting the code at the bottom of the document for best practice reasons. Also, jQuery was never mentioned in the question.
  • Sagar V
    Sagar V over 5 years
    @SrinivasML please try to remove extra spaces in code block. FYI you can also make it as a snippet.
  • techhunter
    techhunter over 5 years
    I didn't get your first point. and regarding second point , I have posted jquery and js both.