Intridea Company Blog
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.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.
The Intridea Blogs
Blog Archive
- January 2010 (5)
- November 2009 (4)
- October 2009 (4)
- September 2009 (2)
- August 2009 (5)
- July 2009 (3)
- June 2009 (7)
- May 2009 (4)
- April 2009 (6)
- March 2009 (15)
- February 2009 (18)
- January 2009 (4)
- December 2008 (2)
- November 2008 (3)
- October 2008 (7)
- September 2008 (9)
- August 2008 (2)
- July 2008 (7)
- June 2008 (14)
- May 2008 (5)
- April 2008 (14)
- March 2008 (6)
- February 2008 (5)
- January 2008 (6)
- December 2007 (5)
- November 2007 (5)
- October 2007 (7)
- September 2007 (2)
- August 2007 (7)
- July 2007 (4)
- June 2007 (3)
- April 2007 (1)
Michael Bleigh