For example if I use this code: $('#iddoesnotexist').remove(); I will not receive an error if this id is not in the page, how to make to show an error?
By default this behaviour was chosen because otherwise jQuery would regularly throw NullReference Exceptions, but this is what I am looking for...
3 Answers 3
You can create your own jQuery extension, I suppose. I would* write it as an assertion:
$.fn.mustExist = function() {
if(!this.length) {
throw new Error("Collection was empty.");
}
return this;
};
And during development:
$('#iddoesnotexist').mustExist().remove();
* Actually, I wouldn't use jQuery; document.getElementById also protects you from this kind of thing ;)
Comments
If you want this behavior to be default for all DOM selection, you can create a wrapper function for the jQuery function.
var my_$ = function(selector) {
var result = jQuery.apply(this, arguments);
if (typeof selector === "string" && !result.length)
throw new Error("No matches found");
return result;
};
my_$("#foobar"); // No matches found
Be sure to use your own reference instead of overwriting the jQuery or $ identifiers.
Comments
See:
jQuery Debugging and http://jqueryfordesigners.com/debugging-tools/ and http://www.jquery4u.com/utilities/live-jquery-debugging-firebug/ and http://samdutton.wordpress.com/2010/09/16/jquery-debugging-tips/ and http://trainofthoughts.org/blog/2007/03/16/jquery-plugin-debug/
for jQuery debugging articles. And, as mentioned in the comments, the simplest way to debug is using console.log.
console.logor set breakpoints in devtools, or use firequery, multiple options as you can see