mbleigh / mbleigh.github.com

My blog and website.

This URL has Read+Write access

mbleigh.github.com / _posts / 2009-06-19-quick-tip-railsy-array-checks-in-jquery.textile
100644 27 lines (19 sloc) 0.938 kb

layout: post
title: “Quick Tip: Railsy Array Checks in jQuery”
-

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.empty = 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...
}