What I Do When My jQuery Code Doesn’t Work

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.

Print | posted @ Friday, March 13, 2009 1:12 AM

Comments on this entry:

Gravatar # re: What I Do When My jQuery Code Doesn’t Work
by jeff at 3/14/2009 4:27 PM

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.

-J
  
Gravatar # re: What I Do When My jQuery Code Doesn’t Work
by scott at 3/14/2009 10:14 PM

@jeff - Good point!
  
Gravatar # re: What I Do When My jQuery Code Doesn’t Work
by Joel D'Souza at 3/16/2009 1:16 AM

A simpler option would be to write a firebug console.log wrapper like this one:
fragged.org
  
Comments have been closed on this topic.