Make sure you’ve got a jQuery object

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:


function annoyingAlert($btn, msg){
    $btn = ($btn.jquery) ? $btn : $($btn) ;

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.');

One thought on “Make sure you’ve got a jQuery object

  1. Pingback: Some code snippet updates… | Error 601

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s