Skip to content

Instantly share code, notes, and snippets.

@mfields
Created May 10, 2011 14:17
Show Gist options
  • Save mfields/964552 to your computer and use it in GitHub Desktop.
Save mfields/964552 to your computer and use it in GitHub Desktop.
Hide submit button if it exists.
/* Hide submit button if it exists. */
var button = document.getElementById( 'my_submit_button' );
if ( null !== button && 'style' in button && 'display' in button.style ) {
button.style.display = 'none';
}
@mfields
Copy link
Author

mfields commented May 10, 2011

Still getting comfortable with javascript here ... This code was taken from a recent project where I needed to hide an html element. Firebug would throw errors if the element did not exist on the page. This was the first solution that I came up with that would hide the element if it exists in the document.

Do you think this is excessive?

Is there a better way of doing this?

I realize that that the perfect solution would be to not include the script in documents where the element is not present, but that is really not the goal ... I would like to develop my skills in javascript and part of that IMO is being able to write code that only does what is intended to do using only methods and properties that are available.

Any thoughts are welcome!

@ericmann
Copy link

Looks very solid and does a great job of checking things progressively. Though you might be able to get away with a != rather than an !== for your first check. If document.getElementById( 'my_submit_button' ) fails to find an element, it will return null. So you can check either equality (==) or identicality (===) and get the same result. In the end, it's the addition of a single character, so it doesn't make too much of a difference.

@mfields
Copy link
Author

mfields commented May 10, 2011

Thanks for taking a look! Does checking for (!==) have a larger footprint over (!=)? I know this is something that WordPress core makes a point to do and I'm comfortable knowing when and where to check for such values in php. Javascript's a whole different animal though.

@ericmann
Copy link

The === and == operators behave exactly the same after doing type conversions. In the end, === is faster if the two sides are different types (because it skips type conversion and just returns false) but == is faster if the two types are the same.

In your case, particularly when using Yoda conditions, there's no benefit of using one or the other since you're comparing with null. It becomes a matter of preference.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment