jQuery Object or Bust

We use jQuery in our web app. I’m starting to use more native JavaScript now that browsers are getting better at creating a consistent API for the native DOM and JavaScript features. But there’s still a lot of usefulness in jQuery, and sometimes when a function requires an input be a jQuery (DOM) object, we’ll need to check it and wrap it pass it to jQuery if it’s not already a jQuery object. (Alright kids, let’s see how many times can we say jQuery in a single paragraph!)

I’ve already written about this a couple times, and it keeps coming up because I keep trying to make it more efficient. Of course, the native document.getElementById(‘id’) and document.querySelectorAll(‘sel’) are usually the fastest way to get a DOM element, but if you still need that as a jQuery object, you gotta call jQuery anyway, so… Let’s try to speed that up, even if just a little bit.

Here’s the latest iteration of this (handy?) function:

function $$(el){
    var $el = el,
        id_prefix = /##|#:|id:/;
    // we only need to run this if el is not already a jQuery object
    if (!$el.jquery) {
        // special case for (faster?) handling of id
        // using a "special" id-only selector:
        //  "##", "#:", or "id:"
        // (this will tolerate crazy non-standard ids)
        // document.getElementyById("foo.bar/baz") ==
        // $$("##foo.bar/baz") == $$("#:foo.bar/baz") == $$("id:foo.bar/baz")
        if (el.search(id_prefix) === 0) {
            el = el.replace(id_prefix, "");
            $el = $(document.getElementById(el));
        }
        // NOW try the standard jQuery selector
        else {
            $el = $(el);
        }
    }
    return $el;
}

// here's how we use it:
// attaching cached object on $$ for fun
$$.emailInput = $$("input[type='email']");
// now we can use jQuery's methods on it
$$.emailInput.on("focus", function(){
    this.value = "";
});

That’s it. This should be faster if we pass a selector that is an id (with special syntax), and will tolerate silly non-standard id values that could contain other strings that would mean something else in the context of a CSS-type selector (like dots for class, colons for pseudo-selectors, etc.).

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s