Make jQuery throw error if it doesn't match element

Usually, when I select an element with jQuery, I would prefer it to give me an error if it does not find the corresponding element.

For example, I just had an error in which this happened, because I changed the class of the ul element:

 $('ul.some-list').append(listItem) 

Is there a convenient way to ensure that my jQuery call matches the element?

+8
javascript jquery dom jquery-selectors
Jun 25 '11 at 19:40
source share
2 answers

You can make a plugin to use to ensure that the jQuery object is not empty:

 $.fn.ensure = function() { if (this.length === 0) throw "Empty jQuery result." return this; } 

Using:

 $('ul.some-list').ensure().append(listItem); 
+11
Jun 25 2018-11-11T00:
source share

In my case, I wanted it to automatically apply to everything, so I changed the jQuery constructor. I suggest you use this only during development to catch bugs, but do not interfere in your production so as not to confuse others. Since this is not an error, I just used console logging. However, I added a commented cast if you would rather use this:

 var jQueryInit = $.fn.init; $.fn.init = function(arg1, arg2, rootjQuery) { var element = new jQueryInit(arg1, arg2, rootjQuery); if (arg1 && element.length === 0) { console.log(arg1 +" doesn't exist"); // throw arg1 +" doesn't exist" } return element; }; 

I'm sorry that in jQuery there was no way to enable this during dev.

In case someone wonders ... if the selector returns the result set when there are no valid matches, this is an intentional decision by jQuery developers. This means that you can apply some code to a set of elements, even if it is likely that they will not be. A good example is the comments on the page or the checkboxes. If he throws an error when no elements were found, you will have to add existence checks to your code. The following topic contains additional information: https://stackoverflow.com/a/212960/

This is a great feature for saving production code. However, it can really bite you in the ass, developing if you make a small typo; or if you try to select an identifier named "foobar" when you must select a class called "foobar".

+6
Jun 14 '12 at 7:21
source share



All Articles