JQuery exception if item does not exist

I work with jQuery, and I need to get any exception (with any operation) at any time if I attach some event or try to perform some action with elements (obtained from the selector) that do not exist. Is there some kind of internal "strict" mode in jQuery for this problem?

+4
source share
3 answers

No no.

However, you can 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(...); 

As an alternative:

 function $s() { return $.apply(this, arguments).checkEmpty(); } $s('...').bind(...); 
+5
source

Check this post for "exists" processing methods.

Exists in jquery

+1
source

No, this is the beauty of jQuery.

You can 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 will not mask empty sets returned with find() or filter() and the like, but humm ...

0
source

Source: https://habr.com/ru/post/1309440/


All Articles