Clever DOM with jQuery

Rowan Lewis’ blog is back and has a nice little article with 5 jQuery tips. Now, jQuery is not completely unknown to me, I saw it passing by on my Google Reader once, but I never really had a look at it. Now I did, and it adds an interesting new angle to Javascript programming.

As you may know there are different programming paradigms. There’s Object-Oriented Programming (Java, C++), Functional Programming (Haskell, LISP?), Procedural Programming (C, Pascal) and some more. One that people are not often aware of, but do use a lot is Declarative Programming. In Declarative programming you do not explain the computer how to get some result, but you describe what result you want and the computer will figure how to get that result. Sounds science-fiction-y to you? Ever wrote an SQL query? Have you noticed how it’s different from writing code in PHP, C, or Java? In a SQL you don’t say “open this table, look at the first row, see if the ‘first_name’ field is ‘Zef’ and the ‘last_name’ field is ‘Hemel’, if so return this row, then continue to the next row and do the same thing” or something like that. You say “give me all rows where ‘first_name’ is ‘Zef’ and ‘last_name’ is ‘Hemel’”. The database will figure out how to actually achieve that result most efficiently. Yes, probably internally there is some kind of a for-loop involved and some if-statements, but you don’t have to worry about those. You specify what you want and the database does the hard work quickly and efficiently.

Ever wrote a regular expression? Then you also programmed in a declarative way. You describe what you’re looking for in a string, not how you would actually go about and check this. If you want to find a string of 4–7 characters where each character is an ‘a’, ‘b’ or ‘c’ you would just write “[a-c]{4,7}”. The interpreter does the rest.

Now why am I telling you this. jQuery adds a bit of declarative programming to Javascript. Javascript has always had this a bit with its Xpath support (another declarative language — probably all query languages are declarative languages), but this makes this kind of programming very simple to use. An example that Rowan gives:

$("a").not("[href^=/]").not("[href^=#]").append("^");

This finds all “a” elements (links) excluding those whose “href” attribute (the URL) starts with either “/” or “#”, it then appends a little piece of HTML code to those elements. Note how you don’t specify how to walk the HTML DOM tree and check if the element you’re looking at is actually an “a” element and if has those “href” attributes, you just specify what you want and jQuery will do the work. Isn’t that elegant?

Read some more of Rowan’s tips here or have a look at the jQuery website.