Why is document.GetElementById returning null [duplicate]

泪湿孤枕 提交于 2019-11-26 06:44:43

问题


I\'ve been using document.GetElementById succesfully but from some time on I can\'t make it work again. Old pages in which I used it still work but things as simple as this:

<html>
<head>
 <title>no title</title> 
 <script type=\"text/javascript\">
 document.getElementById(\"ThisWillBeNull\").innerHTML = \"Why is this null?\";
 </script>
</head>
<body>
 <div id=\"ThisWillBeNull\"></div>
</body>
</html>

Are giving me \"document.getElementById(\"parsedOutput\") is null\" all the time now. It doesnt matter if I use Firefox or Chrome or which extensions i have enabled or what headers I use for the html, it\'s always null and I can\'t find what could be wrong.

Thanks for your input =)


回答1:


The page is rendered top to bottom. You code executes immediately after it's parsed. At the time of execution, the div does not exist yet. You need to wrap it in an window.onload function.




回答2:


Try this:

 <script type="text/javascript">
  window.onload = function() {
   document.getElementById("ThisWillBeNull").innerHTML = "Why is this null?";
  }
 </script>



回答3:


Without window.onload your script is never invoked. Javascript is an event based language so without an explicit event like onload, onclick, onmouseover, the scripts are not run.

<script type="text/javascript">  
  window.onload = function(){  
   document.getElementById("ThisWillBeNull").innerHTML = "Why is this null?";  
  }
</script>

Onload event:

The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.

https://developer.mozilla.org/en/DOM/window.onload




回答4:


Timing.

The document isn't ready, when you're getting the element.

You have to wait until the document is ready, before retrieving the element.




回答5:


The browser is going to execute that script as soon as it finds it. At that point, the rest of the document hasn't loaded yet — there isn't any element with that id yet. If you run that code after that part of the document is loaded, it will work fine.




回答6:


<script type="text/javascript">
  window.onload += function() {
   document.getElementById("ThisWillBeNull").innerHTML = "Why is this null?";
  }
 </script>

Use += to assign more eventHandlers to onload event of document.



来源:https://stackoverflow.com/questions/2632137/why-is-document-getelementbyid-returning-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!