Passionate Development From Journeyman to Master

Defensive programming with jQuery

Sometimes it's good to code defensively and put those extra checks "just in case".
This is especially true if your front end code are generated or rendered dynamically.

I have often encountered Javascript code that tries to access certain HTML element that doesn't exists.
Usually this is caused by the following scenario:
Developer 1 creates the HTML display and Javascript accessing a certain HTML element on the display
Developer 2 comes along few months down the track to do a change request to remove that HTML element.
Developer 2 isn't aware of that there is Javascript code associated with HTML element and he/she doesn't
do proper testing or just ignore the Javascript warning.

Now of course there's no excuse for Developer 2 to be more thorough - but Developer 1 can
also does his part better by programming more defensively.

The scenario above can be easily avoided. If you are using jQuery, you can check the existence of an element by using this simple
code: ``` javascript if ( $('#myDiv').length ) $('#myDiv').show(); ```
The code above is straight from the jQuery - Frequently Asked Questions page.
I sometimes use this sort of code myself, it works for me - but yeah this is before I found the jQuery FAQ page ``` javascript if ( $( '#myDiv' ) != null ){ $('#myDiv').show(); ```

I tend to do this nowadays especially for the code that I know other developers will muck around in the future.

jquery