Skip to content

Instantly share code, notes, and snippets.

@felquis
Last active September 7, 2015 04:10
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 felquis/054ccc291216c9628e00 to your computer and use it in GitHub Desktop.
Save felquis/054ccc291216c9628e00 to your computer and use it in GitHub Desktop.
The `undefined` kind of issue
/*
Return the same of `.get(index)` method,
but if the return of `.get` is undefined
this method will return an empty array `[]`
and NOT an `undefined`
Useful to make sure things wont break if
an element isn't in the DOM
*/
var getThat = function (index) {
return this.get(index) || []
}
jQuery.fn.extend({
getThat: getThat
});
/*
So...
*/
jQuery('.not-in-dom').getThat(0).innerHTML = 'Hi'; // It doesn't throw error
// but
jQuery('.not-in-dom').get(0).innerHTML = 'Hi'; // Throw can't read `innerHTML` from `undefined`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment