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
}

Leave a comment

Archives