Aug 27, 2007

Why jQuery works

Its fundamental philosophy, centering on collections of DOM Elements, puts it squarely where most Javascript developers program most. By contrast, other frameworks, like Prototype and Dojo, take a functional approach. Sure, they’re fully capable of addressing DOM Elements, just like jQuery, but these other frameworks make entirely different choices. Prototype, for one, fancies itself a true Object Oriented extension of Javascript’s paltry native offerings. In pursuit of true object-orientedness, its developers have put a substantial amount of time into developing object-oriented classes for different types of functionality. A class for forms, a class for elements, a class for events. It goes on and on. It’s perfectly possible to write clean, good-looking Prototype code. And Prototype can emulate one of the best things about jQuery’s focus on DOM Element collections: its chainability. But jQuery conceives of modern Javascript development the way many major players in the Javascript community are starting to see it: as DOM Scripting first and foremost. For those of us whose Javascriptprogramming focuses primarily on page elements, and Isuspect that’s most of us, jQuery makes the work dead simple.

Most jQuery methods start with the collection of elements, using the handy support for CSS3, XPath, and a slew of custom expressions (like :visible, which returns only visible elements, and :checked, which returns only checked form fields). Once you obtain a group of elements, the fun begins. Add .fadeIn(“slow”) and each of the elements will fade in—slowly. But we’re not done. Without skipping a beat, add .addClass(“thisIsDamnFun”). Each element will get the class “thisIsDamnFun.” It is, isn’t it? And it can go on from there. Add .click(function() { alert(“Hello”) }); to throw up an alert box when any of the elements are clicked. Add .append(“Hello”) and the word hello will be appended to the end of each of the matched elements. Cool, huh?

Now that you’ve seen the power of jQuery methods, how do we get the element collection in the first place? Happily, we have CSS (1-3) at our disposal, as well as a limited subset of XPath, and some nice custom expressions thrown in for good measure. When I say CSS3, I mean it. jQuery supports the ~ selector, :not(expr), attributes via [@ attr=’whatever’]. XPath support is a bit more limited, but most of the good stuff is here. The / and // operators are available, as are parent and preceding sibling axes. jQuery supports :first, :last, and :eq(n), a slimmed down version of [position() = n]. Finally, jQuery supports testing for contained elements via [tag- Name]. And because the jQuery parses operates on XHTML, it can be easily co-opted for parsing raw XML from AJAX requests. And of course, jQuery has the full complement of AJAX methods through $.ajax, and $().load.

No comments:

Post a Comment