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


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.

jeff Saturday, March 14, 2009
Just a heads up - make _sure_ you remove the console.log(...) from all of your scripts before releasing. That script is dependent upon the users browser having firebug installed; if firebug is not installed script will break.

Seems pretty obvious, but I have seen this happen in the past.

scott Saturday, March 14, 2009
@jeff - Good point!
Joel D'Souza Monday, March 16, 2009
A simpler option would be to write a firebug console.log wrapper like this one:
Comments are closed.