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.

3 comments:

Unknown said...


Trik Mudah Cara Bermain Slot Online Bagi Pemula
Panduan Cara Bermain Blackjack Online
Panduan Terlengkap Cara Bermain Judi Bola Maxbet
Indobola303 | Situs Judi Bola Online Sbobet Terbaik
Panduan Judi Online Tata Cara Main Dragon Tiger Untuk Pemula

Sig Sauer Laser Sight said...

The Sig Sauer P238 Laser pistol is available in at 5 1/2 inches long and is one mean little lug weapon. You have actually got one already as well as you're seeking the absolute best laser sight for your Sig P238 since it eventually may also conserve your life. Given that your Sig frequently stays in a hidden holster inside your waistband, you require a Sig P365 Laser that is most likely to fit your holster as well as also be powerful and easy to use. Sig 365

Gouse said...

"Great introduction to using jQuery in Scala! The explanation about how to precisely select and manipulate DOM elements with jQuery is clear and concise. It’s really helpful for beginners transitioning from JavaScript to Scala, especially when integrating with web development. Looking forward to more tutorials on combining Scala with front-end libraries. Thanks for sharing!"
Digital Marketing Course In Ameerpet

Post a Comment