Prototype: in the shadow of jQuery

Prototype is a rival to jQuery. Not that there is much contest. jQuery is in much wider use and much more actively developed. Still, Prototype does exist and similar things to what jQuery does.

The syntax and usage of Prototype show both similarities and differences to jQuery. You can compare the following pieces of Prototype code to what I wrote about jQuery in an earlier blog post. Before we begin using Prototype to manipulate the DOM we need to make sure it is loaded.

document.observe('dom:loaded', function ()
    // The DOM has been loaded

There are two element selectors in Prototype. The first only selects based on ID. The second uses CSS syntax.

$("bottom");        // by ID
$$("hgroup");       // by tag
$$(".ticket");      // by class
$$("em:empty");     // by pseudo class
$$("h2[title]");    // by tag, has attribute
$$("img[alt='']");  // by tag, has attribute value
$$("a.dead:empty"); // combination of selectors

The ID selector will always refer to a single element, since IDs are unique. The CSS selector will always give back an array of elements. To apply some function to them we have to iterate over them or apply a map.

$$(".warning").each(function (element) {
    element.insert({ before: "Warning: " });

$$(".error").invoke("insert", { before: "Error: " });

For the rest of the Prototype’s functionality I refer you to the Prototype API documentation.

Ajax via Prototype

Of course Prototype can do Ajax as well.

$("button").observe("click", function () {
	$("output").innerHTML = "processing...";
	new Ajax.Request("Page.aspx/Uppercase", {
	    method: "POST",
	    contentType: "application/json",
	    encoding: "utf-8",
	    postBody: Object.toJSON({ text: $("input").value }),
	    onSuccess: function (response) {
	        $("output").innerHTML = response.responseJSON.d.Text;

This is the Prototype version of the client side code when calling a web method in ASP.NET Web Forms as I described in another blog post.


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 )

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