Friday, November 14, 2008

Simple Javascript Object Check

Alright this is something fairly simple but it is useful when you want to have javascript check if an object exists before trying to manipulate it.  As we should know, javascript will die if you try to do an action on an object that doesn't exist.  This is part of the simplicity and low-weight of javascript that makes it great for the web.

So before you try to do anything to an object that might not exist on a particular page, put in the following line of code:

if (document.getElementById('the_id_of_the_object') != undefined)
{
     //code goes here
}

Again, something super simple but may save you some problems in you're building a larger site with pages that might not have the same objects but share the same scripts.

No comments: