Question

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?

EDIT2: doing $placeHolder.getElementsByTagName(tagname).length

works if the element isn't defined, but if it is an element like this: <anElement></anElement>

$placeHolder.getElementsByTagName(tagname).length returns true, and it executes the statement when there is nothing in the element. Trying this test:

if ($placeHolder.getElementsByTagName(tagname)[0].firstChild.data == null)

doesn't work either.

Was it helpful?

Solution

First need to check if there are elements with a specific tagname in your $placeHolder. getElementsByTagName returns NodeList so you can check its length, this way:

if( $placeHolder.getElementsByTagName(tagname).length > 0 )
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top