Applying JavaScript actions to an ID, which doesn’t exist, creates an undefined error.
As an example consider the following HTML. The DIV has been assigned the id introMain, but is incorrectly referenced in the JavaScript as intromain.
<html>
<head>
<title></title>
<meta content="">
<style></style>
</head>
<body>
<div id="introMain" style="display:none;" >Intro text </div>
<script type="text/javascript">
var item = document.getElementById('introMain');
if (item != undefined) {
document.getElementById('introMain').style.display='block';
}
else {
document.getElementById('introMain').style.display='none';
}
</script>
</body>
</html>
The associated error is given below:
TypeError: document.getElementById(...) is null
document.getElementById("intromain").style.display='block';
To avoid a potential error when interacting with a DIV or other element on a web page I like to first check to ensure that the element exists.
To ensure that the entry exists it can be tested as to whether it is undefined.
if (typeof(item) != "undefined") {
actions here
}
The updated JavaScript with a test for the definition included
<html>
<head>
<title></title>
<meta content="">
<style></style>
</head>
<body>
<div id="introMain" style="display:none;" >Intro text </div>
<script type="text/javascript">
if (typeof("intromain") != "undefined") {
document.getElementById("introMain").style.display='block';
}
</script>
</body>
</html>
I have used a number of well known web sites recently which assumed that a form element existed.
There is an assumption that scripts will be loaded for trackers, beacons and such like. Failure to load the referenced script causes an error preventing much of the page from working.


