22.1.06 # jQuery

Jon Resig comes out with jQuery, a new lightweight javascript library.

A specific feature of jQuery is the $ function, adopted from the prototype framework. In prototype the $ function is a simple wrapper around the heavily used DOM method document.getElementById, accepting multiple ID's as arguments.

Jon's implementation is more powerful, as it

  • accepts general CSS selectors and …
  • … a useful subset of XPath expressions as arguments.
  • uses lazy evaluation of the arguments by an internal object.
  • returns that internal query object to allow call chains.

Just to get the idea, the following example uses plain DOM to change the text color of all paragraph elements with class attribute of "remark" to green :

var p = document.getElementsByTagName("p");
for (var i=0; i<p.length; i++)
   if (p[i].getAttribute("class") == "remark")
      p[i].style.color = "green";

Using jQuery we can write now:

$("a").filter(".remark").css("color", "green");
// or ..
$("a[@class='remark']").css("color", "green");

I really like this concept, especially the use of the paradigma:

A function, that deals with a unique object and doesn't have a specific return value, should always return that object.


0 comments