Back to Blog

Get in Touch

Quick Tip: Railsy Array Checks in jQuery

By Michael Bleigh June 19, 2009 in jquery, quick tip, array, convenience

Missing

I love the any? and empty? convenience methods that Rails and Ruby provide, they make conditional statements much easier to read. I also really dislike the default method of checking this behavior in jQuery:

if ($('some.element').length > 0) {
  // ...do something
}

Well, luckily jQuery is ridiculously easy to extend, so why not just mix that functionality in with a couple of quick shot plugin methods? Just add this javascript sometime after you include jQuery:

jQuery.fn.any = function() {
  return (this.length > 0);
}

jQuery.fn.none = function() {
  return (this.length == 0);
}

That’s all you have to do! Now we can make the same call as before, but it looks a little cleaner:

if ($('some.element').any()) {
  // do something more readably...
}

UPDATE: Apologies, I added in the empty bit as a last-second update to the post and forgot to check and realize that empty() is part of jQuery core. Updated the name to none instead.

Medium

Michael Bleigh

Michael has been with Intridea since 2007 and works to build Intridea's portfolio of products. With many years of experience working as both a designer and a developer, Michael specializes in helping to bridge the gap between the back-end development and the front-end design of a project. Michael is a prolific member of the Ruby on Rails community, having released popular open source libraries such as OmniAuth and spoken at conferences including RailsConf and RubyConf.

More posts by Michael Bleigh

Michael Bleigh

To the troubling idea isn't about what signal you're sending to your employee...

Michael Bleigh

Node.js has a pattern that I personally enjoy: if you require a directory, it...

Michael Bleigh

Last weekend I had the opportunity to speak at RubyConf 2012 about a topic th...