Skip to content

Instantly share code, notes, and snippets.

@craigweston
Last active April 7, 2016 14:00
Show Gist options
  • Save craigweston/3cc98cf0e752bc62896e to your computer and use it in GitHub Desktop.
Save craigweston/3cc98cf0e752bc62896e to your computer and use it in GitHub Desktop.
$.ensure - Extending jQuery to guarantee passed in variable (of selector string, plain DOM element or jQuery instance) will be a jQuery instance without double wrapping it
// double wrapping performance test: http://jsperf.com/check-jquery-wrap
$.extend({
ensure: function(el) {
return !(el instanceof jQuery) ? $(el) : el;
}
});
// example use
function doSomethingWithEl(el) {
el = $.ensure(el);
el.addClass('someClass'); // we expect el to represent a jQuery instance here
}
var el;
// call it with a string selector
el = '.elClass';
doSomethingWithEl(el);
// call it with a dom element selector
el = document.getElementById('elId');
doSomethingWithEl(el);
// call it with jQuery if thats what we already have
el = document.getElementById('elId')
doSomethingWithEl(el);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment