简体   繁体   中英

Uncaught TypeError: Cannot read property 'appendChild' of null after calling getElementById()

I've just started learning JavaScript (properly :D) and I'm having a hard time dealing with the above mentioned error. The browser that I'm using is the latest Google Chrome on a Debian Jessie 64bit system. The code is embedded inside the <script/> tag of my page:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
    <head/>

    <body bgcolor="white">
        <p><u>Counter:</u></p>
        <div id="counter"/>
        <p><u>Temperature conversion:</u></p>
        <div id="temperature"/>
        <script type="text/javascript">
            function printRange(_from, _to) {
                // ...
            }

            function fahrenheitToCelsius(fahrenheits) {
                return 5/9 * (fahrenheits - 32);
            }

            document.getElementById("counter").innerHTML = printRange(2,-10); // (1)

            var fahrenheits = prompt("Enter Fahreheit degrees", 50);
            var celsius = fahrenheitToCelsius(fahrenheits);
            var para = document.createElement("p");
            para.textContent = fahrenheits + "F = " + celsius + "oC";
            document.getElementById("temperature").appendChild(para); // (2)
        </script>
    </body>
</html>

The document.getElementById("counter") (marked with 1 ) is working fine however the mentioned error occurs at document.getElementById("temperature") (marked with 2 ) even though both <div/> s are basically one after the other and both appear before the <script/> tag where these are being referenced. I do understand that the error comes from document.getElementById("temperature") returning null but I haven't got the faintest idea WHY the script is unable to find the given ID through this function call.

There are only a certain subset of elements that you can use without a closing tag. That is the implicit use case of /> . The subset is known as "void elements" .

As a result of div not being one of those elements, your <div/> tag is simply rendered as <div> without a closing tag. The first document.getElementById("counter").innerHTML = printRange(2,-10); // (1) document.getElementById("counter").innerHTML = printRange(2,-10); // (1) summarily wipes out the rest of the page with the results of the call to printRange.

Close your elements properly.

<div id="counter"></div>

technically self-closing tags are disallowed in HTML 4.x but are allowed in XHTML -- could you try not self-closing the div tags?

jsfiddle

<div id="temperature"></div>

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