I'm new to jQuery and I'd like to simplify the handling of elements it can't find, which is a fairly common problem. The following code shows what I mean:
var category = $('select#Category');
Now, I can inspect the returned variable to see if it wasn't found, but I'd definitely prefer an exception being thrown automatically in this case. Is this at all possible with jQuery? If not, is there some common idiom for implementing such automatic error checking on top of jQuery?
jQuery :not() SelectorThe :not() selector selects all elements except the specified element. This is mostly used together with another selector to select everything except the specified element in a group (like in the example above).
The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack.
Technically you can throw an exception (throw an error). If you use throw together with try and catch , you can control program flow and generate custom error messages.
The jQuery Object: The Wrapped Set: Selectors return a jQuery object known as the "wrapped set," which is an array-like structure that contains all the selected DOM elements. You can iterate over the wrapped set like an array or access individual elements via the indexer ($(sel)[0] for example).
I'm not sure of any existing functionality to do that, but I think this should work for you if you put it at the top of the page before using jQuery, but after loading it:
(function(){
var _$ = $;
$ = function(){
var $res = _$.apply(0, arguments);
if(!$res.length && typeof arguments[0] === 'string')
throw 'No element Found: ' + arguments[0];
return $res;
}
$ = _$.extend(true, $, _$);
})();
JSFiddle Example
I simply use this approach:
if (category.length == 1) {
// node has been found (and is the only one in the dom)
}
I think that throwing an exception is not a good idea :P
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With