Saturday, September 7, 2013

Having problems testing if an XML element exists

Having problems testing if an XML element exists

My script works fine when all of the elements I'm searching for are
declared, but I cannot for the life of me figure out how to test if an
element exists or not.
$placeHolder.getElementsByTagName(tagname)[0].firstChild.data; // works if
the element exists
I've tried testing out these lines of code:
if (!($placeHolder.getElementsByTagName(tagname)[0].firstChild.data in
window)) //always true
{
alert("this doesn't exist");
return $noValue;
}
else
return $placeHolder.getElementsByTagName(tagname)[0].firstChild.data;
Even if the element exists the if statement is true and executes the first
block of code, if it doesn't exist it just generates an error saying that
'$placeHolder.getElementsByTagName(tagname)[0].firstChild.data' is
undefined.
Next I tried this method:
if (typeof $placeHolder.getElementsByTagName(tagname)[0].firstChild.data
== "undefined")
{
alert("this doesn't exist");
return $noValue;
}
else
return $placeHolder.getElementsByTagName(tagname)[0].firstChild.data;
This one actually works correctly if the element does exist, but still
yields the same error as the one above it.
I tried making a try catch block, but I ran into the same problem of
having to test if the element was undefined. D:<
All I need is a simple way to see if the element in question exists (i.e.
if it is or isn't undefined.) Is there a method I'm not aware of or am I
doing something wrong?

No comments:

Post a Comment