When I started this website some years ago, I think it was somewhere around 2008, I used Prototype JS for all the client-side interaction required for a small blog like this:

And if I remember correctly, the first version of this website (2006-2007) was not a PHP application but the web-interface of a full-blown Lotus Notes / Domino 6 database which I hosted on my own little Domino Server. I used this Lotus Notes document repository primarily for the knowledge- and document management during my studies at the University of Paderborn, but I extended the database with a web interface that offered a subset of the documents over the Domino's HTTP-Task with an user-interface which is quite similar the this website as it is now.

This early version of AndyK Docs did use some custom JavaScript functions for a simple AJAX search interface, but did not utilize Prototype or any other JavaScript framework as we know them today.

Why did I use Prototype JS?

Prototype JS was first released in 2005 and back then was one the the most-popular JavaScript-frameworks. I first noticed Prototype JS when I stumbled upon the scriptaculous (or script.aculo.us) JavaScript library for dynamic web-user-interfaces and visual effects. The Script.aculo.us library is a great collection of JavaScript functions for enhancing web pages which neat visual-effects (fade-in, fade-out, puff, pulsate, highlight, shake), useful web-controls such as a Slider, an Autocompletion-control or an InPlace-Editor and convenient utility-functions for creating DOM elements. And the foundation for all these functions is the Prototype JS Library.

Besides the animation capabilities of the scriptaculous library, Prototype offers a wide range of fundamental functionality which can be used in all major browser versions. The functions I used the most where certainly the dollar-selector-functions and the HTML element-related functions for creating and manipulating DOM elements. Followed by the Array- and Enumerable-extensions (such as the each-method, the unique- and the reverse-function). And finally the Prototype's Ajax-capabilities:
The Ajax.Request, Ajax.PeriodicalUpdater and Ajax.Updater functions allow easy access to remote APIs and data.

In short:
  • Prototype JS was one of the first JavaScript Frameworks at all
  • The scriptaculous animation framework depends on Prototype JS
  • Prototype and Scriptaculous offer all the functionality a web-developer could ever ask for
  • Prototype offers reliable support for all (relevant) browsers

Why migrate from Prototype to jQuery?

So why would I go through the pain of a migration, if Prototype (and Scriptaculous) is such a feature-rich and reliable JavaScript library?
The answer is short and simple:

Prototype is dead*. And jQuery is on fire.
* Or at least less alive than jQuery ;-)

Even though the code of Prototype framework has a very high quality and the compatibility with the different browser-types is still extremely good (and seems almost timeless to me), the version history of the Prototype Framework draws a clear picture and proves my point, that is is time to move on to something new:

  • Prototype 1.5.0 (January, 2007)
  • Prototype 1.5.1 (May, 2007)
  • Prototype 1.5.1.1 (June, 2007)
  • Prototype 1.6.0 (November, 2007)
  • Prototype 1.6.0.2 (January, 2008)
  • Prototype 1.6.0.3 (September, 2008)
  • Prototype 1.6.1 (September, 2009)

As of today (2010-04-05) the latest release of Prototype JS is the version 1.6.1 and was published in September 2009 - almost one year ago.

The prototype.js file for itself is already 136 KB heavy and there is no (official) packed and minified version available for download. Scriptaculous pointed in the right direction with its modular approach - loading only the libraries that are actually required for the current scenario, but the problem is Prototype with its all-in-one architecture. The Prototype library offers way to much functionality and isn't targeted towards a lightweight architecture.

And that's where jQuery comes into play.
  • jQuery is (compressed or un-compressed) considerably smaller than Prototype (which is only available in an uncompressed version).
    Yes, I must admit that compressed or uncompressed simply doesn't matter that much when the JavaScript file is delivery with GZIP compression, but (for me) it still feels better to know that there an officially minified version out there.
  • jQuery selectors are a hell of a lot faster than selectors of other JavaScript frameworks (Prototype, MooTools, YUI, Dojo) (see: Taskspeed Report for jQuery 1.4.2 and Prototype 1.6.0.3)
  • jQuery is the library that is used the most across the web (see: JavaScript Usage Statistics).
  • (I think) jQuery carries less dead weight with it than Prototype: Prototype has functions for every conceivable purpose, but are rarely used by the average user, while jQuery tries to keep the core library as small as possible. In some cases Prototype has even two function for the same purpose --> jQuery is more concise.
  • Visual Studio 2010 will have Intellisense support for jQuery. Yeah.
  • jQuery has an very long list of great plug-ins available for download at http://plug-ins.jquery.com/
  • And I have the impression that jQuery has a more active community, because it is the most popular JavaScript Framework (see: JavaScript Usage Statistics ^^)
IMAGE/PNG: The Taskspeed Benchmark Result-Chart for the comparison of the jQuery 1.3.2, jQuery 1.4.1, jQuery 1.4.2, Prototype 1.6.1, MooTools 1.2.4, Dojo 1.4.1 and YUI 3.0.0 JavaScript framework performance, by browser (Firefox 3.5, Firefox 3.6, Opera, Safari, Chrome, Internet Explorer 8, Internet Explorer 7, Internet Explorer 6). (jQuery, 2010, Prototype)

In the end I don't want to convert you to one framework or the other. Both frameworks are reliable, have a huge community, many useful plug-ins and (in the end) a (very) similar syntax and functionality.
I liked Prototype JS a lot in the past, but I think it's time to move on to something new now.

Migration steps: Transforming your JavaScript code from Prototype to jQuery

Even though the syntax of Prototype and jQuery do not differ that much and there many similarities between both JavaScript frameworks, there are a couple of things to keep in mind while migrating.

  1. Selecting DOM elements

    The function that are used the most are the dollar-utility methods for selecting DOM elements:
    • $(elementId) function calls must be handled with caution because a missing '#'-sign in front of the selector can cause you a lot of grief.

      For a quick-migration you can simply use a text-editor that supports Regular Expressions (e.g. UltraEdit, Notepad , Eclipse), search for this pattern /$(['"]([a-z0-9_-]+)['"])/gim and replace it with this pattern $('#$1').

      Or, you can try the "Prototype-To-jQuery-Migration-Script" I created along with this little migration-guide. The JavaScript-based online-migration-script automates the transformation of your Prototype code to the jQuery syntax and may speed up your Prototype-migration a little. Just try out the online migration script or see the next section where I'll describe it in more detail.

      IMAGE/PNG: Screenshot: Migrating from Prototype JS to jQuery using Regular Expressions. Searching for dollar-function calls that will be replaced with a new selector. (jQuery, Migration, 2010, Prototype, Screenshot, Tutorial)
      But, I would recommend you to manually review every single reference of a $(elementId) function-call in your code in order to ensure that you have an '#' in front of your elementId where you need one - this will spare you long hours of debugging.
      And it's a good chance to review your code and improve your code-quality.
    • Prototype's $$(selector) function can (without further review) be replaced with a simple $(selector) call.
      Just replace all occurrences of "$$(" with "$(". (--> Simple search & replace)
    • Once all first-level selectors are migrated you can move on with the sub-element-selector functions.
      Since the Prototype Element.select()-function has a matching part in the jQuery library, you can simply replace all occurrences of ".select(" with ".find(".
  2. Get and set the content of HTML elements

    Function-calls that I encountered the second-most during my very own migration process were function calls for reading/writing the values of form-elements and getting/setting the HTML-contents of DOM-elements:
    • $F(element | selector | elementId) or $(element | selector | elementId).getValue() function calls must be transformed to match the jQuery syntax: $(element | selector | elementId).val()

      At first you must make sure that you migrated all $F(elementId) function calls to match the new jQuery syntax.
      This can be done with these two little regular expressions.
      Find-Pattern: /$F(['"]([a-z0-9_-]+)['"])/gim
      Replace-Pattern: $F('#$1')

      The regular expression for finding and transforming the relevant code segments with $F function-calls could look like this:
      Find-Pattern: /$F(['"]([#a-z0-9_-]+)['"])/gim
      Replace-Pattern: $('$1').val()

      Using these regular-expression for the parts of your migration process that are pure and simple monkey work can save you a lot of time, but keep in mind that they are not perfect.

    • Code blocks that use the standard innerHTML JavaScript property ( --> $(element | selector | elementId).innerHTML ) for manipulating the content of DOM elements must use the .html() function of the jQuery library.

      Get HTML content
      Migrating the innerHTML property to the jQuery syntax is a little more tricky than the examples listed before, but you can give it a try with these regular expressions.
      Find-Pattern: /$(['"]([^)]+)['"]).innerHTMLs*=s*(["']*.+["']*);/gim
      Replace-Pattern: $('#$1').html($2);

      Set HTML content
      Migrating the innerHTML property to the jQuery syntax.
      Find-Pattern: /).innerHTML([^=]*);/gim
      Replace-Pattern: ).html()$1;

      If you want to test, adapt or improve the regular expressions listed here with your JavaScript code, you can do so with an awesome website for testing RegExps:
      http://gskinner.com/RegExr/

    • The functionality of the Prototype-Element.update() method for setting the contents of DOM elements is as well as the .innerHTML property reflected by the jQuery .html()-function.
      The migration from .update() to .html() can be done with a simple search & replace operation.
  3. Updating the style and CSS of DOM elements

    The functions and methods for setting new style attributes, adding CSS class names to HTML elements or removing classes are completely alike in both JavaScript frameworks and require very little migration-efforts.
    A simple set of search & replace operations will suffice to migrate your Prototype code with HTML-style related functions to the jQuery syntax.
    • Replace all occurrences of ".setStyle(" with ".css("
    • Replace all occurrences of ".getStyle(" with ".css("
    • Replace all occurrences of ".classNames()" with ".attr('className')"
    • Replace all occurrences of ".hasClassName(" with ".hasClass("
    • Replace all occurrences of ".toggleClassName(" with ".toggleClass("
    • Replace all occurrences of ".addClassName(" with ".addClass("
    • Replace all occurrences of ".removeClassName(" with ".removeClass("
  4. Getting and setting element attributes

    Another common type of operations that are used quite often are actions like reading the href-attribute of a link-element, setting the id-attribute of a newly created DOM element or setting the width and height of a div-container.
    • The .readAttribute( attributeName ) function allows you to retrieve and process the value of any given attribute. The jQuery equivalent to this function is .attr( attributeName ).
      In order to transform this function to jQuery you can simply replace all occurrences of the string ".readAttribute(" with ".attr(".
    • The .writeAttribute( attributeName ) function allows you to create or update attributes of DOM elements. The jQuery equivalent to this function is again the .attr( attributeName ) method.
      In order to transform this function to jQuery you can simply replace all occurrences of the string ".writeAttribute(" with ".attr(".
    • The functions for reading the width & height of HTML elements are again pretty much the same in both frameworks (with the little reservation that Prototype has no core-capabilities for setting the width or height of DOM elements).
      • Replace all occurrences of ".getWidth()" with ".width()"
      • Replace all occurrences of ".getHeight()" with ".height()"
    • The Boolean-function which allows you to check whether a given element is empty or not differ a little in Prototype JS and jQuery but can be transformed back and forth with a simple search & replace.
      • Replace all occurrences of ".empty()" with ".is(':empty')"
  5. Events

    Binding events to DOM-elements is another important topic for all JavaScript frameworks and is of course equally well implemented in Prototype and jQuery - even though jQuery offers more native event-handlers such as click, dblclick, mouseover, keyup and many more.
    • Event.observe and $(elementId).observe functions calls in Prototype must be transformed to $(#elementId).bind(...) in order to attach an event to an HTML element with jQuery.
      • Due to the somewhat complicated structure of the Event.observe function calls I cannot provide you with a regular expression that eases the migration-process.
    • $(elementId).observe functions calls in Prototype must be transformed to $(#elementId).bind(...) in order to attach an event to an HTML element with jQuery.
      • Replace all occurrences of the string ".observe(" with its jQuery equivalent ".bind(".
    • Another commonly used function-type that is highly useful are the onDomReady functions, which allow you to execute arbitrary functions and methods once the web-page is completely loaded.
      • Replace ".observe('dom:loaded'," with "$(document).ready("
  6. Ajax requests

    The migration-procedure between the Prototype-Ajax syntax and the jQuery-Ajax syntax is a little bit more complicated than the examples above. Again, the concept and the syntax do not differ significantly, but this special case is a little bit too tricky (for me) to create a regular expression for it which does the transformation.
    • Search for the text string "Ajax.Request" in your Prototype JavaScript code and manually transform the signature of the Prototype Ajax.Request to match the jQuery.ajax function signature.

      If you have a text editor that supports multi-line regular expression searches, you can also the following RegExp to highlight all code blocks using Prototype Ajax.Request.
      Find-Pattern: new Ajax.Request(([^});] )});
      Replace-Pattern: <none>

      See the comparison-table below for further migration instructions.

    • Search for the text string "PeriodicalUpdater" in your Prototype JavaScript code and manually transform the signature of the function to match the jQuery syntax.
    • Search for the text string "Ajax.Updater" in your Prototype JavaScript code and manually transform the signature of the function to match the jQuery syntax.
  7. Creating new DOM elements

    Creating HTML elements from scratch is another frequently used function of a JavaScript framework. And because the syntax is pretty much the same in jQuery and Prototype, the migration is nothing than a simple search & replace operation.
    • new Element() function calls can easily be migrated with a simple search & replace operation.
      • Replace "new Element(" with "$("
 

Automatically migrate Prototype to jQuery

I assembled a little JavaScript-based application that can help you transform your old Prototype code to the jQuery syntax.
The migration-script combines all the migration-steps and regular-expressions listed in the sections above and and run executes them on the code you can paste into the input-area of the online-migration tool:

-> Using my little Prototype-to-jQuery migration script can speed-up your migration process a little. But please let me know if it really worked for you.

Comparing Prototype to jQuery

The following section contains a comparison-table which contrasts some of the frequently used functions of the Prototype framework with their jQuery counterparts and highlights the differences.
The table is quite big - so it cannot be displayed with its full witdh, but you can also view the jQuery-migration cheat sheet (in its full size) if you open either the HTML-file, the PNG-Image or the PDF-document below:


Prototype JS jQuery

Command / Function Description Command / Function Description
Selecting DOM elements $( elementId | element )
  • If a string is passed to the dollar-function, it will return the DOM element with the matching ID attribute.
  • If an HTML element is passed, an extended version of the element is returned.
  • It is also possible to pass an array of elementIds or elements to the $-selector.
$( selector | element ) or jQuery( selector | element ) The jQuery-dollar-function accepts a string containing a CSS selector which is then used to match a set of elements.
  • selector:
    If a selector string is passed to the dollar-function, it will return the DOM elements which match the given CSS-selector.
  • element:
    If an HTML element is passed, an extended version of the element is returned.
The main difference is between the Prototype dollar-function and the jQuery counterpart is, that the jQuery-version expects and CSS-selector - while the Prototype-version requires and element-id.

So the jQuery-equivalent to the dollar-function would rather be the Prototype-dollar-dollar-function (-> $$(selector)).

Note:
Because this function is the one that is used the most in both frameworks, this will be the parts of your JavaScript that will need the most attention during a migration.
  • A Prototype-based function which depends on code like this "var targetElement = $('searchresultcontainer');"  WILL certainly fail when using jQuery - even though the syntax and signature of both versions of the dollar-function is quite similar. The jQuery-variant needs to look like this to work:

    var targetElement = $('#searchresultcontainer');

The missing "#" in $-function calls is bound to be biggest source of bug during a migration process from Prototype JS to jQuery.
  $$( selector ) Takes an arbitrary number of CSS selectors and returns a document-order array of extended DOM elements that match any of them. The task of selecting HTML elements which CSS selectors is performed by the simple dollar-function: $( selector )

Visit these pages for more information about CSS selectors:
  $(element).select( selector ) The select-function takes one or more CSS selectors and allows you to select HTML elements which are sub-nodes of the calling DOM element. $(element).find( selector ) Gets the descendants of each element in the current set of matched elements, filtered by a selector.
  • This function works alike  Prototype's select-function and can therefore easily be migrated with a simple search and replace.
Get / Set the content of DOM elements $F( element ) or $(inputelement).getValue() Returns the value of a form control (textbox, textarea, radiobutton, checkbox, ...). $( 'selector' ).val() Returns the value of the calling element.

$(element).innerHTML Returns HTML code of all text nodes and child elements of the parent DOM node. The property can also be used to set the contents of an HTML element.

But note, this property is not specific to the Prototype framework - but just a standard property of all HTML nodes.
$(element).html() Gets the HTML source ode of the calling HTML element.

$(element).update( text Or HTML code ) Sets the HTML code of the calling element. $(element).html( text Or HTML code ) Sets the HTML source ode of the calling HTML element.

$(element).innerHTML.stripTags() or $(element).innerText Returns the contents of the calling element; stripped from any HTML tags. $(element).text() Returns the combined text contents of the calling element, including their descendants.
Update the Style of DOM elements $(element).setStyle( style(s) ) The Prototype setStyle functions modifies the CSS style properties of the calling HTML element. $(element).css( propertyName, value ) Sets the value of a HTML element's style property.

Example:
  • $(selector).css('backgroundColor', 'red')
  $(element).getStyle( propertyName ) Returns the given CSS property value of the calling HTML element. $(element).css( propertyName ) Get the value of the calling HTML element's style property.

Example:
  • $(element).css('backgroundColor')
    // -> 'red'

$(element).classNames() Returns a set of CSS class names assigned to the calling HTML element (e.g. [ "class1", "class2", "class3" ]). $(element).attr('className') The list of all CSS classes assigned to an HTML element can only be determined by reading the className-attribute.

But unlike the Prototype-version, this approach will only return a simple string list of all CSS class names assigned to an HTML node (e.g. "class1 class2 class3").

$(element).hasClassName( className ) Checks whether the calling element has the given CSS className. $(element).hasClass( className ) Determine whether any of the matched elements are assigned the given class.

The hasClassName function works exactly alike in both frameworks. The only difference is the slightly shorter name of the jQuery version.

$(element).toggleClassName( className ) Toggles an element's className: If the element did not have the CSS class before - it will be assigned; otherwise it will be removed from the HTML element. $(element).toggleClass( className ) Adds or removes one or more CSS class names for each element in the set of matched elements, depending on whether the element had the class name before or not.

The toggleClassName function works exactly alike in both frameworks. The only difference is the slightly shorter name of the jQuery version.

$(element).addClassName( className ) Adds the specified class name to the calling HTML element. $(element).addClass( className(s) ) Adds the specified class-name(s) to each element of the set of matched elements.

The addClassName function works exactly alike in both frameworks. The only difference is the slightly shorter name of the jQuery version.

$(element).removeClassName( className ) Removes the specified class name from the calling HTML element, if it was assigned before. $(element).removeClass( className(s) ) Removes the specified class-name(s) from each element in the set of matches elements.

The removeClassName function works exactly alike in both frameworks. The only difference is the slightly shorter name of the jQuery version.
Get/set DOM element attributes $(element).readAttribute( attributeName ) Returns the value of calling element's attribute or null if attribute name does not exist. $(element).attr( attributeName ) Gets the value of an attribute for the first element in the set of matched elements.

$(element).writeAttribute( attribute(s) ) Adds, specifies or removes attributes to HTML elements. $(element).attr( attributeName, value ) Creates a new element attribute and/or sets the value for the given attribute.

The only difference is that the jQuery .attr() function is not able to remove attributes from HTML elements. For this task you must use the specialized .removeAttr() function.
  $(element).getWidth()
$(element).getHeight()
Returns the width / height (number of pixels) of the calling HTML element. $(element).width()
$(element).height()
Get the current computed width / height for the first element in the set of matched elements.
  Prototype JS has no core functionality which allows you to set the width or height of HTML elements. $(element).width(value)
$(element).height(value)
Sets the width or height of the calling HTML element.
  $(element).empty() Returns true if the element does not contain any characters (except whitespaces); otherwise false. $(element).is(':empty') Utilizes the .is() selector for checking if the current element has no child nodes (including text nodes). Returns true if the current element is empty; otherwise false.
Events Event.observe(element, eventName, handler) Registers an event handler on a DOM element. $('selector').bind(eventType, handler) Attach a event-handler to the set of matched elements.

jQuery offers a long list of explicit event-functions in addition to the abstract bind-function for DOM-events. Examples:
  • click(): OnClick event
  • dblClick() Double-Click
  • hover(): Binds two event handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements.
  • keydown(): Is triggered when a key is pressed.
  Event.stopObserving(element, eventName, handler) Unregisters one or more event handlers from the given element. $(selector).unbind(eventtype, handler) Removes a previously-attached event handler from the set of matched DOM-elements.
  document.observe("dom:loaded", function() {
...
});
The dom:loaded event is fired immediately after the HTML document is fully loaded. $(document).ready() The document-ready event is fired as soon as the whole DOM has been assembled.

I think the jQuery-version is much more reliable than the Prototype approach.
  Event.findElement(event, tagName) Returns the element that fired the event. event.target

Example:
  • $("#button").click(function(e) {
    var btn = $(event.target);
    });
The DOM element that initiated the event.

Another way to access the element that caused the event is this:
  • $("#button").click(function(e) {
    var btn = $(this);
    });
Ajax
new Ajax.Request(url[, options]) Creates and processes and AJAX request to the specified url. $.ajax( settings )
Performs an asynchronous HTTP request (ajax).
  new Ajax.PeriodicalUpdater(container, url[, options]) Periodically performs an AJAX request and updates a container%u2019s contents based on the response text. There is no PeriodicalUpdater for jQuery, but you can build one yourself:

var periodicalUpdater = function() {
    $.ajax({
        url: 'http://www.example.com/api/get/status.html',
        dataType: 'text',
        success: function(code) {
            $("#statusContainer").html(code);
        }
    });
};

setInterval(periodicalUpdater, 1000);
  new Ajax.Updater(container, url[, options]) Updates the given container element with response text from the ajax-request to the specified url. There is no Ajax.Updater for jQuery, but you can easily build one yourself:

$.ajax({
    url: 'http://www.example.com/api/get/content.html',
    dataType: 'text',
    success: function(code) {
        $("#container").html(code);
    }
});
Create new DOM elements
new Element(tagName[, attributes]) Create a new DOM element (just like with document.createElement('div')). There is no direct equivalent for the Prototype "new Element()"-command within the jQuery Core, but you can use a simple document.createElement(tagName) instead or use the following jQuery plug-in:
jQuery.create() - jQuery plug-in to create HTML elements

Or you can simply create a DOM element by passing the html-code:
  • var link = $("<a/>", { class: "link", text: "New Link", href: "http://api.jquery.com/jQuery/" });
  • var link = $('<a href="http://jquery.com"></a>');
  Element.insert(element, { position: content }) Insert the content object before, after, at the top of, or at the bottom of element. Instead of a single function for all purposes (inserting elements before or after a given element) jQuery has one specialized function for every single purpose:

$(element).append()
$(element).appendTo()

$(element).prepend()
$(element).prependTo()

$(element).before()
$(element).after()

$(element).insertBefore()
$(element).insertAfter()

Even though I think the jQuery versions of "Element.insert()"  are more versatile, I like the "simpler" Prototype-version better.
append(content): Inserts the content element to the end of each element in the set of matched elements.

appendTo(target): Inserts every element in the set of matches elements to the target element.

prepend(content): Inserts the content element to the beginning of each element in the set of matched elements.

prependTo(target): Insert every element in the set of matched elements to the beginning of the target element.

before(target): Insert the content element before each element in the set of matched elements.

after(target): Insert the content element after each element in the set of matched elements.

insertBefore(target): Insert every element in the set of matched elements before the target element.

insertAfter(target): Insert every element in the set of matched elements after the target element.
  $(element).identify() Gets the element's id if it is assigned; otherwise a new id is generated, assigned and returned. I guess because jQuery does not have a core function for creating new DOM elements, there was no need for a function which automatically assigns new ids to them.

Workarounds:
  • Get id attribute with jQuery:
    $(element).attr('id')
  • Set id attribute with jQuery:
    $(element).attr('id', 'YourCustomId')
Forms
Form.Element.disable() Disables a form control - prevents user from editing the form elements. There is no direct equivalent to Prototypes "Form.Element.disable()" in the jQuery core, but you can easily prohibit the editing of form elements with only very little code:
  • $('form:first').attr("disabled", "disabled")
  • $(formElement).find('input, textarea').each(function(i) { $(this).attr("readonly","readonly"); });
  Form.Element.enable() Enables a previously disabled form control. There is no direct equivalent to Prototypes "Form.Element.disable()" in the jQuery core, but you can easily allow the editing of form elements with only very little code:
  • $('form:first').removeAttr("disabled")
  • $(formElement).find('input, textarea').each(function(i) { $(this).removeAttr("readonly"); });
Traversing Arrays, Sets and Collections $$(selector).each(function(s, i) {
var currentElement = s;
})
A handy notation for the well known for-loop. The each-operator iterates over all members of the given set of matches elements. .each( function(index, Element) )
Iterate over a jQuery object, executing a function for each matched element.

The syntax of the each-iterator is exactly alike in both frameworks, but can also be used slightly different in jQuery:
  • $(selector).each(function(i) {
    var currentElement = $(this);
    });
Miscellaneous functions & utilities new PeriodicalExecuter(function(pe) { ... }, interval) Executes a given function every n-seconds. Again, there is no direct substitute in jQuery for a periodical updater, but it can be build quite easily (without even depending on jQuery).

Example of a simple (non-jQuery-specific)
periodical-updater (*1000 milliseconds = 1 second):
  • var periodicalExecuter = function() { ... };
    setInterval(periodicalExecuter, 1000);

Is it worth it?

A migration is always a lot of pain and you might ask yourself if it is worth it.

And for myself the answer is yes.
It took me a couple of hours of (mostly dull) work, but I took the opportunity to refactor and some of my old code along the migration process and made it "better".
AND I've got the good feeling that I am no longer using a dead horse (even though it was a good one).

Links & Resources

Here are a couple of links that can help you with your own migration process or might help you decide whether to migrate your Prototype code to jQuery, or not.

The two JavaScript frameworks Tools & Resources JavaScript framework performance Further Articles
7 Comments so far
  1. Andreas Koch on Friday, 16 April 2010 22:53

    ... speaking of Prototype’s lack of fresh releases:
    A new version of Prototype was just released: Prototype 1.7 RC1
    Emotion:doh

    Anyhow, I still like jQuery better.

    Greetings
    - AndyK

  2. Zhai Yue on Wednesday, 16 March 2011 11:54
    Great work Andreas! This is a wonderful guide that I could ever hoped. I really like the part why you convince yourself and people migrate to jQuery from Prototype is a better idea..Thank you.
  3. Christopher on Wednesday, 17 August 2011 15:05
    Thanks Andy. Great overview.

    However I found a few things that are wrong:

    => Creating new DOM elements: Replace "new Element(" with "$("
    That won't work...
    How it should be:
    Replace "new Element('tag')" with "$()"

    => Replace all occurrences of ".getWidth()" with ".width()"
    Prototype's getWidth will return the absolute width of the element (including padding and border) while jQuery will simply return the value of the css width property (without the css unit "px", "%", ...).
    How it should be:
    Replace all occurrences of ".getWidth()" with ".outerWidth()"

    Same applies to ".getHeight()" and ".height()".

    => Replace all occurrences of ".classNames()" with ".attr('className')"
    Prototype's classNames() is returning an object while ".attr('className')" will return a string.
    Also in jQuery 1.6 they changed the way they treat element attributes and properties.
    So this should rather become ".prop('className')".

    Concerning ajax requests:
    I think it would be helpful to mention that by default Prototype's Ajax.Request will do a POST while jQuery's $.ajax will by default perform a GET request.


    Cheers,
    Christopher
  4. Christopher on Wednesday, 17 August 2011 15:07
    Oh, and you might wanna fix your comment system... all my formatting (line breaks etc.) got lost in the comment above.
  5. TweeZz on Friday, 07 October 2011 9:26
    Hi,

    2 small questions:
    - How many lines of js code did your 'AndyK Docs' have when you made the switch?

    - Did you have your own prototype js classes and did you use 'inheritance'?
  6. Andreas Koch on Friday, 07 October 2011 21:10
    Hej TweeZz,
    I just checked my old svn repository and looked up how much Prototype and script.aculo.us based JavaScript I had for the application.

    It have been 7921 lines of code (including comments and all) that I migrated from Prototype JS and script.aculo.us to jQuery at that time.

    The code itself wasn't too fancy and didn't use much inheritance.

    Greetings
      –  Andreas
  7. Andreas Koch on Saturday, 08 October 2011 0:04
    Hej Christopher,
    thank you for your detailed suggestions. I haven't looked into this Prototype to jQuery stuff in a while, but I will have a look on your feedback and let you know when I updated this article.

    And thank you too for reminding me that my commenting system really does suck. Not even that your formatting was lost, TweeZz ^^ also found out today that I had a full-blown cross-site scripting bug in my commenting system as well.

    I fixed both issues just now. Your formatting should be restored and TweeZz shouldn't be able to extend my site with funny alert boxes anymore ... but don't take this as a challenge ;-)

    Thank you both for your feedback AND your bug reports.
    ... and sorry for the late reply. I have been busy lately.

    Greetings
      –  Andreas
Name:

Website:


Attachments

File-Icon: application/pdf
File-Icon: image/png
File-Icon: image/png
File-Icon: image/png
File-Icon: application/pdf
File-Icon: text/html
File-Icon: image/png
File-Icon: image/png
File-Icon: image/png
File-Icon: text/html
File-Icon: text/plain
File-Icon: image/png
File-Icon: image/png
File-Icon: application/x-javascript