2 ms·
You can also add assertions to jQuery about the length of the chain: jQuery.fn.assertLength = function(i) { if (this.length != i) { throw "Expected
by simonw 18y ago
You can also add assertions to jQuery about the length of the chain:
jQuery.fn.assertLength = function(i) {
if (this.length != i) {
throw "Expected " + i + " matching elements, selection was: " + this.get();
}
return this;
}
If you're using jQuery 1.3 (with its new selector property), a better implementation might be:
jQuery.fn.assertLength = function(i) {
if (this.length != i) {
throw "Expected " + i + " matching elements, got " + this.length + ", selector was: " + this.selector;
}
return this;
}
You can then introduce the assertLength method in to your chains like so:
$('div#intro a').assertLength(3).click(...)
If the number of matched elements doesn't match the expected, you get a descriptive exception raised which stops execution and shows up in the error console.