Making jQuery throw an error when it returns an empty collection

Posted . Visible to the public.

When you are working with jQuery selectors and collections, many times you want to know if the collection actually contains the elements you wanted to select. Here's a tiny jQuery plugin that does just that.

$.fn.ensure = ->
  if (@length == 0) then throw 'Empty jQuery collection'
  this

Use it like this:

$('input[id$=_cache]').ensure()
> Console: "Uncaught Empty jQuery collection"
Dominik Schöler
Last edit
Dominik Schöler
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2016-06-15 09:15)