Skip to content

Instantly share code, notes, and snippets.

@devinrhode2
Last active November 27, 2018 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devinrhode2/3a81a45d11fe29f0c9f45be5876c220a to your computer and use it in GitHub Desktop.
Save devinrhode2/3a81a45d11fe29f0c9f45be5876c220a to your computer and use it in GitHub Desktop.
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