The easy way to avoid errors while accessing an html element/object is to check whether the object exists in the page before accessing or not.
All the modern browsers support document.getElementById to get the object/element in the page. So we can use this to check the object's existence.
In this function, we use document.getElementById that Returns the element that's ID is specified. If there is no element with the given id, this function document.getElementById returns null.
function chkObject (theVal)
{
if (document.getElementById(theVal) != null)
{
return true;
}
else
{
return false;
}
}
Note:
Implementations that do not know whether attributes are of type ID or not are expected to return null. getElementById was introduced in DOM Level 1 for HTML documents and moved to all documents in DOM Level 2.
Example:
This following example will check for the input boxes/elements 'age' and 'address'
and return true for age and false for address.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML>
<HEAD>
<TITLE>Check if an object/element exists or not
</TITLE>
<script language="javascript">
function chkObject (theVal)
{
if (document.getElementById(theVal) != null)
{
return true;
}
else
{
return false;
}
}
</script>
</HEAD>
<BODY>
<input type="text" id="age" value="10"/>
<input type="button" class="wizNormalBtn" value="check age" onclick="if(chkObject('age'))alert('age exists');"/>
<input type="button" class="wizNormalBtn" value="check address" onclick="if(!chkObject('address'))alert('address does not exist');"/>
</BODY>
</HTML>
Check for the input element 'age' returns true

Figure 1:
Check for the input element 'address' returns false

Figure 2: