Last active
April 7, 2016 14:00
-
-
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
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
// 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