Testing for Existence of Element

Sorry, this is probably a really basic question, but, I have the following code:

<script language="javascript">
<!--
// Max number of items to show/hide
var maxItems = 10;

// Function to show/hide divs based on ID
function showHideLayers(showItem)
{
	// Loop through array of tab IDs
	for (i = 1; i < maxItems + 1; i++) {
		
		// Init vars
		var element, elementStyle, elementID;
		elementID = "listings_station_" + i;
		
		// Get element (for different browsers)
		if( document.getElementById ) // this is the way the standards work
			element = document.getElementById(elementID);
		else if( document.all ) // this is the way old msie versions work
			element = document.all[elementID];
		else if( document.layers ) // this is the way nn4 works
			element = document.layers[elementID];
		
		// Set var to CSS style of element
		elementStyle = element.style;
		
		// Set element display
		elementStyle.display = (elementID == showItem) ? 'block' : 'none';
	} // End loop
} // End function
-->
</script>

Which is designed to hide all but one of a group of DIVs with consecutive IDs in the form “listings_stations_<number>”. The problem is, I won’t know how many of these DIVS there will be. I know a maximum possible number though.

The script as-is works, but obviously throws up errors trying to get handles to non-existent elements/objects. How can I check an element exists before getting and setting style properties for it? I’d like a solution that works for all three browser-types the script currently works with.

Sorry if this is a really basic question. Funnily enough, I’ve been writing JavaScript for a while, but have very little experience using it with the DOM for browser-scripting.

a|x

OK, this seems to work.

// Max number of items to show/hide
var maxItems = 22;

// Function to show/hide divs based on ID
function ell_listings_accordion(showItem)
{
	// Loop through elements
	for (i = 1; i < maxItems + 1; i++) {
		// Init vars
		var element, elementStyle, elementID;
		// Construct ID string
		elementID = "listings_station_" + i;
		
		// Attempt to get element (for different browsers)
		if( document.getElementById ) // this is the way the standards work
			element = document.getElementById(elementID);
		else if( document.all ) // this is the way old msie versions work
			element = document.all[elementID];
		else if( document.layers ) // this is the way nn4 works
			element = document.layers[elementID];
		
		// If element found, set style
		if(element) {
			// Set var to CSS style of element
			elementStyle = element.style;
			// Set element display (show if showItem, otherwise hide)
			elementStyle.display = (elementID == showItem) ? 'block' : 'none';
		}		
	} // End loop
} // End function

Cheers guys.

a|x