.lengthis your friend when debugging jQuery. Because even if:
document.getElementById('nonexistent');
will return nullin JavaScript, using the jQuery selector will return an object and produce true:
if(!document.getElementById('nonexistent')) {
alert('not here!');
}
if(!$('#nonexistent')) {
alert('here, here!');
}
It means that:
$('#nonexistent').doSomething().doSomethingElse().whatever();
Probably not throwing errors, so it will be difficult for you to find out what is “not working” in the chain.
However, checking the length of an object works:
if(!$('#nonexistent').length) {
alert('not here!');
}
jQuery is designed to be silent, as one of its main uses is chaining. And if prototype selectors or methods return null or false in the chain, using jQuery will generate null-referenced errors more often than most inexperienced programmers want.
, , , , . :
var debug = ['hide','show'],
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]));
}
}
, 'hide', , :
$('#nonexistent').hide();
Fiddle: http://jsfiddle.net/B4XQx/