3

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...

balexandre
75.5k47 gold badges240 silver badges352 bronze badges
asked Jul 5, 2012 at 0:28
4
  • 3
    I use console.log for debugging :) Commented Jul 5, 2012 at 0:30
  • You can use console.log or set breakpoints in devtools, or use firequery, multiple options as you can see Commented Jul 5, 2012 at 0:32
  • 1
    I think the title was a bad choice. As I understand it, you look for an option that makes jQuery throws errors on empty matches but many people are just looking at the title and recommending debugging tools... Commented Jul 5, 2012 at 0:40
  • I took a look in Firebug console log and didn't found the errors for the specific code... (I checked for show strict warnings too.) Commented Jul 5, 2012 at 0:51

3 Answers 3

7

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 ;)

answered Jul 5, 2012 at 0:35
Sign up to request clarification or add additional context in comments.

Comments

1

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

0
answered Jul 5, 2012 at 0:35

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.