Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Converting from Prototype to jQuery (v1)

Converting from Prototype to jQuery

Selecting DOM elements

Prototype’s selector returns DOM elements.

$("element_id");
// return: <div id="element_id"></div>

jQuery’s selector returns an object which may contain 0+n DOM elements.

jQuery("#element_id"); // or $("#element_id");
// return: [div#element_id]

The equivalent is:

jQuery("#element_id")[0];
// return: <div id="element_id"></div>

Binding functions to contexts

Prototype has a bind function.

function.bind(context);

jQuery binds with a proxy.

jQuery.proxy(function, context);

Iterating over an array

Prototype adds an each method to Array.

Array.each(function(item) {
  // ...
});

jQuery can iterate over arrays.

jQuery.each(Array, function(item) {
  // ...
});

But usually you want to iterate over the results of a jQuery selector:

jQuery("#element_id").each(function(index, element) {
  // ...
});

Adding event handlers

Prototype adds the observe method to DOM elements

$("element_id").observe("click", function(event){
  // ...
});

jQuery has the on method (⚠️ bind is deprecated in jQuery) .

jQuery("#element_id").on("click", function(jQueryEvent){
  // ...
});

…or the shorthand click (and others).

jQuery("#element_id").click(function(jQueryEvent){
  // ...
});

The jQueryEvent object is not the same as a regular event object, but target() both work the same.

On DOM Ready

Initializing on DOM ready is done with Prototype’s observe method as:

document.observe("dom:loaded", function() {
  // ...
});

In jQuery:

jQuery(function(){
  // ...
});

Value method

Prototype has .value.

$("#element_id").value;                 // get value
$("#element_id").value = "Hello world"; // set value

jQuery has .val.

jQuery("#element_id").val();              // get value
jQuery("#element_id").val("Hello world"); // set value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.