jQuery.batch Plugin
May 8th, 2008
jQuery methods, in most cases, operate on zero or more matched elements. Getter type methods are an exception. The getter methods only return the results for the first matched element. This is overwhelmingly the typical use-case. However, sometimes you might want to get the results for all matched elements in the jQuery collection. Introducing jQuery.batch, a small extension to jQuery that adds such functionality.
jQuery.batch extends the core with plural forms of the getter methods. Methods like attr now have a sibling named attrs. These new methods operate on the whole jQuery collection, returning an array of results. Here are the pluralized methods that jQuery.batch provides.
- attrs
- styles
- widths
- heights
- vals
- texts
- htmls
In addition with the core methods the jQuery.batch plugin offers its own plugin method: jQuery.fn.batch. This method takes the name of an existing plugin/method attached to jQuery.fn along with any additional arguments to pass along.
-
$('a').batch('attr', 'href');
Of course since jQuery.batch already provides the attrs method that could also be written as.
-
$('a').attrs('href');
Plugin Integration
jQuery.batch makes it easy to integrate with plugins to provide a pluralized sibling by using a method called jQuery.batch.registerPlugin. For example here is the line used within the plugin to register the core methods.
-
$.batch.registerPlugin( 'attr', ['css','styles'], 'offset', 'width', 'height', 'html', 'text', 'val' );
Basically it is just an argument list of method names. Notice that I passed an array for the css method to manually set the pluralized name to something more desirable. Otherwise, it will just append an 's' to the end of the method name.
Get jQuery.batch
You can download, log issues and create feature requests at the plugins home: http://plugins.jquery.com/project/batch

May 9th, 2008 at 8:56 am
The plugin was returning a jQuery collection instead of an Array. I've released 1.0.1 that fixes this issue. I found it while exploring a question on the jQuery support list here: http://snurl.com/28275 [groups.google.com]
May 10th, 2008 at 5:12 pm
Sweet plugin! Would be nice if the plural for "text" was something like "contents" :)
May 10th, 2008 at 5:18 pm
Guy, contents is actually already a [fairly new] jQuery core method. It returns the actual text nodes too. http://docs.jquery.com/Traversing/contents