Julian Jelfs’ Blog

Beware empty/null selectors with jQuery

Posted in Javascript, jQuery, Uncategorized by julianjelfs on April 17, 2009

I encountered a problem today with one of my JavaScript components which I use to wrap and extend the normal checkbox input control. My component uses jQuery to add an onclick event to the underlying dom element as follows:

$(this._element).click(fn);

The problem arises when the underlying element does not actually exists (never mind why). In this case this._element is null. My assumption was that if jQuery did not throw an exception here (which it rarely does) then it would probably just do nothing in this case. My assumption was wrong, as in this case it appears that jQuery will attach the click event handler to the whole document body. This is pretty obvious when you look at the jQuery code itself as the first thing it does is to make sure that you have indeed specified a selector:

jQuery.fn = jQuery.prototype = {
    init: function( selector, context ) {
        // Make sure that a selection was provided
        selector = selector || document;
....

The end result is that the click function I was trying to assign to the checkbox click was actually happening when clicking anything. I’m sure there is a good reason for this but it seems likely a slightly odd default behaviour to me and one to watch out for.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: