Debugging? Break Those Chains - J Query

A chain of jQuery methods is failing some where along the way. The HTML code is as follows:

and the JavaScript code (part of a button click event handler) is as follows:

But when you run the code, the font size isn’t set, and the hidden element isn’t shown.You have Firebug or another JavaScript debugger, but it’s hard to trace through the code. How can you tell where in the chain it is failing?


Break up the chain into individual statements, and store each jQuery object in a variable:

Now you have several debugging options. One is to use the Step Over command in the debugger to single step over each statement and observe your variables and the state of the page after each step.
In this code, you’d want to check $foo and $bar after their values are assigned. What is the value of the .length property of each? That tells you how many DOM elements were selected. Does each object contain the DOM elements you expect? Check the [0],[1], [2], etc., properties to see the DOM elements.
Assuming that $foo contains the correct DOM elements, what happens after the.css() method is called? With Firebug’s CSS Inspector, you’ll find that the CSS font-size property is unchanged after the method call. Wait a minute! It’s font-size,not font size? There’s the problem. Checking the docs, you find that the correct way to write this is either of these:

That’s one problem down, but what about the other one? After $bar is assigned, if we look at its .length property, we’ll see that it is zero. This tells us that we didn’t succeed in selecting any elements. A look at the HTML and JavaScript code will then reveal that we simply misspelled the class name.
Now we can incorporate these two fixes back in the original chain:

These console. log() calls will reveal that $bar does n’t have any elements selected, although we’ve fallen into a trap on the call that attempts to log the font size: we mis spelled font Size in the console.log() call as well!
This is where combining multiple debugging techniques helps: log those variables, use Firebug’s inspectors, read and reread your source code, and have someone else look at the problem too.

jQuery’s chaining helps make it easy to write concise code, but it can get in the way when debugging, because it is hard to step through the individual steps of the chain and see their results. Breaking up the chain into individual statements, even on a temporary basis while debugging, makes this task easier.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd Protection Status

J Query Topics