Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have jQuery throw an exception when an element isn't found?

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?

like image 918
aknuds1 Avatar asked Sep 02 '11 07:09

aknuds1


People also ask

How to use not in jQuery selector?

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

Does throw exception stop execution JavaScript?

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.

Can you throw exceptions in JavaScript?

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.

What does a jQuery selector return?

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


2 Answers

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

like image 104
Paul Avatar answered Nov 24 '22 09:11

Paul


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

like image 45
daveoncode Avatar answered Nov 24 '22 09:11

daveoncode