OdeToCode IC Logo

What I Do When My jQuery Code Doesn’t Work

Friday, March 13, 2009

When my jQuery code doesn’t work, it usually means I’ve done something terribly wrong with my selectors. Thus, my first rule of debugging code that uses jQuery:

Make sure the selector is actually selecting what you want selected.

I can liberally apply rule number one before fiddling with event handlers and method calls that come later, because it’s easy to do and saves me time.

Step 1: Navigate to the page with a problem and open FireBug.* 

Step 2: Type your opening selector in the command bar of the console.

Step 3: Verify the object length is > 0

firebug

If you need to take a look at the objects you’ve selected, then a little console logging inside FireBug goes a long way.

$("div > a").each(function() { console.log($(this).text()) })

I hope this tip saves you as much time as it has saved me!

* Technically, any JavaScript execution environment will work, like the Visual Studio immediate window, but the FireBug / Firefox combination is simple and works every time. Another one I like is  the jsenv bookmarklet from squarefree.com.