paul bennett

Javascript: testing whether elements or properties exist

Posted on: February 1, 2007

PHP has a simple function to test whether a variable or array key is set:

if(isset($somevar)) {
// do PHP stuff
}

I needed the same kind of thing in JavaScript as tests like this were failing:

if(case1 && case1[0].innerHTML && case1[0].innerHTML.length > 0) {
// you won't be doing anything in here, as your browser will cry and complain
}

Seeing as case1 was (intentionally) undefined for my test case, I was getting the error ‘case1 has no properties’. I needed a valid test to see whether something was set or not, or if an object had the property I wanted to check.

Enter typeof();

JavaScript’s typeof function lets you test whether variables are set or if an object actually has that elusive property you’re seeking. Use it like so:


if(typeof(case1) != undefined && typeof(case1[0]) != undefined) {
// do JavaScript stuff without making your browser cry
}

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Archives

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: