3 ms·
Exactly this. It's extremely useful to be able to say "with all document elements that matches this selector (whether there are any or not), do this." It's pos
by wwweston 2y ago
Exactly this. It's extremely useful to be able to say "with all document elements that matches this selector (whether there are any or not), do this."
It's possible it's also situationally useful to say "if there aren't any document elements that match this selector, error out, if so do this with all of them." I'm struggling to imagine a specific situation in which that has compelling advantages (and would be interested in elaboration), but let's say it exists. Then something like this:
$.fn.mustMatch = function(onNoMatch) {
if (!this.length) {
if(typeof onNoMatch == 'function') onNoMatch(this);
else throw "mustMatch failed on selector " + this.selector;
}
return this;
}
would make it easy to explicitly add the guard condition with an invocation like `$("#selector .nonextant").mustMatch().each(function (emt) { /*do this*/ })`, rather than having it invisibly ride along with every comprehension and making the "whether there are any or not" case harder.
And if for some reason one were possessed of the conviction that implicit enforcement of this universally within their project outweighed the advantages of explicit options for both ways, it'd probably be better to patch the jQuery lib for that specific project than enforce it as a standard for everyone worldwide.