Nathan Hoad

Debugging your selectors in jQuery

March 1, 2012

Anyone who has used JQuery for more than 5 minutes has experienced a selector not matching anything. It’s especially fun when the selector is called in a callback, e.g. response handlers from an ajax call, animations finishing, etc.

The solution is usually something simple - a missing fullstop, or a forgotten square brace, or an element on the DOM in the selector was changed from a span to a div. They usually take longer to debug than they should, because the debugging cycle is usually something like this;

So, for example, say you’ve got some Javascript like this:

$(function() {
    # ...
    $.post('/some/url', someData, function(response) {
        $('#foo-element div .bar-element').html(response);
    });
});

And the html response is not being displayed as it should be. So you start console.log()‘ing to infinity to figure out where the problem is, like so;

$(function() {
    # ...
    $.post('/some/url', someData, function(response) {
        console.log($('#foo-element'));
        console.log($('#foo-element div'));
        console.log($('#foo-element .bar-element'));
        console.log(response);
        $('#foo-element div .bar-element').html(response);
    });
});

And then you refresh, get the content to load again, and then check the console to see where the selector returned nothing. Tweak your selectors and try again, with the magic refresh cycle. Instead of doing that, which is annoying, boring and time consuming, I propose this;

$(function() {
    # ...
    $.post('/some/url', someData, function(response) {
        window.debug_elem = $('#foo-element');
        console.log(window.debug_elem);
        $('#foo-element div .bar-element').html(response);
    });
});

Now, refresh your browser once, get the callback to fire, open your console (Webkit has the Developer Tools, Firefox has Firebug, etc) and go to town on window.debug_elem. You can work the whole thing out in the console, in typically less than a minute, fix it, then go back to something more interesting.

I know there are much more involved solutions and libraries for doing stuff like this. But this is a barebones, no nonsense approach that literally has no dependencies. I couldn’t find anything online making this suggestion, even though I’m sure a lot of people doing it. So, enjoy!