Michael Swarts
Michael Swarts

Reputation: 3921

How can I ask JavaScript to hide an element ONLY IF it can be found?

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

Upvotes: 0

Views: 259

Answers (3)

Matthew Lock
Matthew Lock

Reputation: 13486

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";
}

Upvotes: 0

Darko
Darko

Reputation: 38860

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();

Upvotes: 8

deceze
deceze

Reputation: 522165

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

if (element) {
    element.hide();
}

Upvotes: 1

Related Questions