Thursday, October 21, 2010

jQuery exactly 1

jQuery rules. However, it is very very common to see people write $('myselector').something() assuming they match exactly 1 thing. jQuery operates on sets and is just as happy with 0 as 1 as many so our attempt to manipulate that one specific div may go awry unnoticed. A toggle() may be fairly noticable but $('#blah').text(v) may be changing 0 elements for ages before anyone notices.

To avoid having this type of error fly under the radar I find it very helpful to define $1 as a jQuery selection that raises an error if it doesn't match exactly 1 thing. According to Firebug the $ (or jQuery) function is defined as (jQuery 1.4.2):
function (a, b) {
    return new (c.fn.init)(a, b);
So we can simply define $1 as delegating to $:
$1 = function(a, b) {
 var result = $(a, b);
 if (1 != result.length) {
  throw "expected to match exactly one element";
 return result;
Voila! Now we can write $1('someselector') and get a warning there was a js error if our selector doesn't match exactly one thing.

No comments:

Post a Comment