.exists() and does_not_exist() for jQuery
Switch branches/tags
Nothing to show
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.


jQuery Predicates

jQuery Predicates adds two new methods to jQuery:

  • exists returns true if the selection is not empty. For example, $('.preference-pane:visible').exists() returns true if the preference pane is visible.
  • do_not_exist returns true if the selection is empty. For example, $('input.invalid').do_not_exist() returns true if there are no input elements with class invalid.

For your convenience, there are synonyms .exist() and .does_not_exist(), so your code can give a hint as to whether you expect there to be one or many elements. So you can write this:

outstanding_tasks = $('.task.outstanding')

if (outstanding_tasks.exist())

Or perhaps this:

while ($('.notification-banner').does_not_exist()) {
  // ...

See for yourself:

;(function (jq_fn) {		
	jq_fn.exists = function () {
		return !!(this.length);
	jq_fn.exist = jq_fn.exists;
	jq_fn.do_not_exist = function () {
		return !(this.length);
	jq_fn.does_not_exist = jq_fn.do_not_exist;

If you don't want to use jQuery Predicates, by all means continue testing for $('.foo:visible').length or $('input.invalid').length == 0. But wouldn't you agree that it's more elegant to have code that says exactly what it means?

p.s. jQuery Predicates plays well with jQuery Combinators's .ergo(...) and .when(..) methods.

p.p.s I'm writing a book called CoffeeScript Ristretto. Check it out!