.length is your friend when debugging jQuery. Because even if:
document.getElementById('nonexistent');
will return null in JavaScript, using a jQuery selector will return an object and cast true:
if(!document.getElementById('nonexistent')) {
alert('not here!');
}
if(!$('#nonexistent')) {
alert('here, here!');
}
Which means that:
$('#nonexistent').doSomething().doSomethingElse().whatever();
Will probably not throw errors, so you will have a hard time knowing what "didn’t work" in the chain.
However, checking the object length works:
if(!$('#nonexistent').length) {
alert('not here!');
}
jQuery is designed to fail silently, since one of it’s core use cases is chaining. And if selectors or prototype methods would return null or false in the chain, using jQuery would throw null-reference errors more often than most inexperienced programmers would want.
Update
You can probably do your own debugging by modifying the prototypes if in debug mode. I tried this:
var debug = ['hide','show'], // Array of jQuery methods to debug
i = 0, name;
for(; debug[i]; i++) {
name = debug[i];
if (typeof $.fn[name] == 'function') {
$.fn[name] = (function(name, fn) {
return function() {
if ( !this.length ) {
console.warn('No elements selected when calling '+name);
}
fn.apply(this, Array.prototype.slice.call( arguments ));
};
}(name, $.fn[name]));
}
}
Now, whenever I call 'hide', it will warn me if there are no elements in the chain:
$('#nonexistent').hide(); // consoles a warning
Fiddle: http://jsfiddle.net/B4XQx/
error()? Whether this would catch underlying JavaScript errors I'm unsure, though.