views:

134

answers:

3

I have a javascript event handler in one of my SSI files that hides a bunch of elements that may or may not appear on the page that calls the SSI file. As a result, the handler goes smoothly until it cannot find the element I'm asking it to hide and then stops before completing whatever may be left to hide. So, how can I get JavaScript to not get hung up on whether or not the element is on the page and just get through the handler?

Many thanks.
Mike

+1  A: 

Some code would be nice to answer this properly, but what about this:

if (element) {
    element.hide();
}
deceze
Or even more succinctly: element
Hans B PUFAL
To-may-to, To-mah-to. ;)
deceze
actually if using jQuery element will never be null as long as a selection is attempted beforehand. if there is no element then it will just be an empty jQuery array
Darko Z
I know, you said so in your answer. But that's just guessing, the OP didn't specify anything beyond pure Javascript.
deceze
+8  A: 

Depends on how you're getting the element. If you're not using a JS library then you could do something like this:

/* handler begin code */
var el = document.getElementById('myElement');
if (el) {
    //do work
}
/* handler end code */

Its easier if you use something like jQuery, where you can select the element and then even if it doesn't exist any operations on the selected set will not throw an exception

//this will work even if myElement doesn't exist - no exceptions will be thrown
$("#myElement").hide();
Darko Z
A: 

In plain old javascript (no libraries) you just do this for each id you want to hide:

if( document.getElementById("myelementId") ) document.getElementById("myelementId").style.display = "none";

You could put it in a loop too if you liked:

var elementsToHide = ["tom","dick","harry"];

for( var i in elementsToHide ) {
    var element = document.getElementById(elementsToHide[i]);
    if( element ) element.style.display = "none";
}
Matthew Lock