Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
warn on empty jquery selection badSelectorAction devinrhode2
// simple working copy pasta version (requires extendFunction.js, devinrhode2/extendFunction.js
// https://github.com/devinrhode2/extendFunction.js
window.failsafe = 'failsafe';
// Don't like throwing errors? Define $.badSelectorAction to be whatever you want.
function badSelectorAction( selector, context, originalResult ) {
if (window.console && console.warn) {
console.warn( '$(\''+selector+'\') selected nothing. Do $(sel, "failsafe") to silence warning. Context:', context);
}
return originalResult;
}
$.badSelectorAction = badSelectorAction;
//Feel free to stop reading here!
extendFunction('$', function strictSelectorOverride( args, oldjQuery ) {
var selector = args[0];
var context = args[1];
//if it's not a string or clearly html..
if ( typeof selector !== 'string' ||
( selector.charAt( 0 ) === '<' &&
selector.charAt( selector.length - 1 ) === '>' &&
selector.length >= 3 )
)
{
return oldjQuery.apply(this, arguments);
}
if ( context === 'failsafe' ) {
return oldjQuery.call(this, selector); //don't do apply because context is 'failsafe'
} else {
var result = oldjQuery.apply(this, arguments);
if (typeof result.length === 'number') {
if (result.length > 0) {
return result;
} else {
return $.badSelectorAction.call(this, selector, context, result);
}
} else {
//.length is undefined or not a number, result is unknown, just return it.
return result;
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.