getElementById cannot get the object
There is a sequence when the browser parses the document. Before the page is loaded, or before the corresponding DOM object is loaded, the corresponding object cannot be obtained.
Look at the code below:
<script> var temp = document.getElementById("div"); alert(temp); </script> <body> <div id="div"> <input name="username" id="username" type="text"> <button id="btn">Button</button> </div> </body>
In this code, document.getElementById(“div”)
cannot obtain the object, and alert(temp) will pop up null;
This is because when the browser parses the code in the script tag, the DOM elements in the body have not been loaded, so naturally nothing can be obtained.
Solution: Move the code in the script after the body element.
<body> <div id="div"> <input name="username" id="username" type="text"> <button id="btn">Button</button> </div> <script> var temp = document.getElementById("div"); alert(temp); </script> </body>
Or add window.onload
<script> window.onload = function(){ var temp = document.getElementById("div"); alert(temp); } </script>
Summarize
The above is what the editor introduces to you to solve the problem of document.getElementBy series methods not being able to obtain objects. I hope it will be helpful to you. Thank you very much for your support of the downcodes.com website!