Last active
September 7, 2015 04:10
-
-
Save felquis/054ccc291216c9628e00 to your computer and use it in GitHub Desktop.
The `undefined` kind of issue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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