Making jQuery throw an error when it returns an empty collection

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