So, I’m writing a function that accepts jQuery DOM objects as arguments and sometimes even I forget that I’m supposed to pass a jQuery object when calling the function and pass only a selector. Here’s a short line of code that will make sure your function is working with a jQuery object:
$element = ($element.jquery) ? $element : $($element) ;
…or, if you’d rather check for falsiness and you don’t mind a single-line if
statement maybe just…
if (!$element.jquery) $element = $($element) ;
Yes, it looks completely redundant and the else statement looks weird, but it’s totally cool, man. If you want to make sure your function doesn’t choke because some doofus (like me) forgot to wrap up the selector in $()
, or maybe your element’s id has some weird characters in it and you need to pass the good ol’ document.getElementById('my_id')
as your argument, it’s a tiny chunk of code for a whole bunch of insurance.
Here’s an example of this in action in a function that shows an alert when clicking a button element:
JavaScript:
function annoyingAlert($btn, msg){ $btn = ($btn.jquery) ? $btn : $($btn) ; $btn.click(function(){ alert(msg) } }
HTML (and inline JavaScript):
<button id="this_button">Click Me</button> <script type="text/javascript"> annoyingAlert('#this_button', 'Good job genius, you clicked the button.'); </script>