On Feb 23, 2:33 pm, "Moses" <mosesdinaka...@gmail.comwrote:
Hi All,
Is is possible to catch the error of an undefined element while
creating an object for it.
Consider we are not having an element with id indicator but we
are trying to make the object for it
indicator = document.getElementById('indicator');
Though we dont have any element like 'indicator' we wont get any
error
If no element with id="indicator" exists, then the variable indicator
should be set to null.
<URL:
http://www.w3.org/TR/DOM-Level-2-Cor...ml#ID-getElBId >
but if we try like this
indicator.style.innerHTML = 'Loading'
which throws the error "Indicator has no Properties"
Because you are trying to do something with a property of an object
that doesn't exist. Even if indicator is a reference to DOM element,
its style object doesn't have an innerHTML property, that is a
property of the element itself - maybe.
>
Is it possible to catch the error while creating an object
itself
(ie)
You me e.g.
>
try {
indicator = document.getElementById('indicator');
} catch(e) {
//No Error
It will enter the catch block if there *is* an error.
}
but
try {
indicator.style.innerHTML = 'Loading'
} catch(e) {
// Here we get the error
}
But I need to cache the error while Creating the object itself , ie
If I try to create an object for an undefined element the error
should be thrown.
You're confused. If I understand your question (and it's very likely
I don't), the error occurs because you are incorrectly using
innerHTML.
>
Is it posible.
Yes, test the return value of getElementById to ensure it returns an
object. Then test that the properties of that object are what you
expect before you try to access properties of the properties...
var indicator = document.getElementById('indicator');
if (indicator && typeof indicator.innerHTML == 'string') {
// do something with indicator's innerHTML property
}
--
Rob