I working with jQuery and I need to get anytime and anywere exception (with any operation), if I attach some event or try to perform some action with elements (got from selector) that don't exist. Is there some internal "strict" mode in jQuery for this issue?
Asked
Active
Viewed 6,880 times
3 Answers
7
No, there isn't.
However, you could make a simple plugin for it:
$.fn.checkEmpty = function() {
if (!this.length)
throw new Error("No elements matched by " + this.selector);
return this;
};
$('...').checkEmpty().bind(...);
Alternatively:
function $s() { return $.apply(this, arguments).checkEmpty(); }
$s('...').bind(...);

SLaks
- 868,454
- 176
- 1,908
- 1,964
1
Check this post for ways to handle an "exists"

Community
- 1
- 1

Mark Schultheiss
- 32,614
- 12
- 69
- 100
-
1This does not answer the question. – SLaks May 11 '10 at 17:36
-
Right, the real answer is "no" for strict mode, there are no modes. This just points out some alternatives. – Mark Schultheiss May 12 '10 at 11:49
0
No, this is the beauty of jQuery.
You could create a wrapper function
function myjQuery() {
var res = $.apply(this, arguments);
if (!res.size()) {
throw new Error("No elements matched :(");
};
return res;
};
myjQuery('input').each();
This won't mask empty sets returned by using find()
or filter()
and the like, but humm...

Matt
- 74,352
- 26
- 153
- 180