Defensive programming with jQuery16 Oct 2009 | Comments
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.
Usually this is caused by the following scenario:
Developer 2 comes along few months down the track to do a change request to remove that HTML element.
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
The code above is straight from the jQuery - Frequently Asked Questions page.
I tend to do this nowadays especially for the code that I know other developers will muck around in the future.