Such a problem arises in the course of learning the getElementById () method, and is to be recorded. Before we analyze the problem, we might as well get to know the getElementById () method first. getElementById () method, takes a parameter; Gets the ID of the element. If the corresponding element is found, the element's Htmldivelement object is returned, and NULL is returned if it does not exist.
That's how I came to realize:
HTML code: From the code can be found, I have added <div id= ' box ' > Test div</id>.
<span style= "FONT-SIZE:18PX;" ><! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
JS Code:<span style= "FONT-SIZE:18PX;" >var Box=document.getelementbyid (' box '); Gets the element node ID of box alert (box);</span>
opens the HTML file in a Web page and pops up a null message box.
The correct display should return the Htmldivelement object, why does it appear nul? As you can see from the HTML code, it first executes the JS and then executes the HTML, which is obviously a matter of order. The reason is found, naturally there is a solution. Here we teach you two ways to solve this problem:
1. Move the script call tag to the end of HTML.
To change the HTML code:
<span style= "FONT-SIZE:18PX;" ><! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
2. Use the OnLoad event to handle
Change JS Code
<span style= "FONT-SIZE:18PX;" >window.onload=function () {var box=document.getelementbyid (' box '); Gets the element node ID of box alert (box); };</span>
both of these methods can correctly return the Htmldivelement object. But there is a problem with the display. Firefox, Google and other browsers will display [object Htmldivelement], but only IE will display [object]. This is because all objects of IE are implemented in the form of COM objects.
Summary:
JS's knowledge point is very broken. If you just go ahead and not tidy up and summarize. Then learn the previous knowledge, the knowledge will be forgotten. Such a small problem as summarized above, if not recorded summary, then will not be able to recall in a long time.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
JS NULL problem