简体   繁体   中英

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

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>

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> 

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

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!";
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM