Reputation: 9691
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.
Upvotes: 2
Views: 249
Reputation: 452
technically self-closing tags are disallowed in HTML 4.x but are allowed in XHTML -- could you try not self-closing the div tags?
<div id="temperature"></div>
Upvotes: 0
Reputation: 82287
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)
summarily wipes out the rest of the page with the results of the call to printRange.
Close your elements properly.
<div id="counter"></div>
Upvotes: 5