Porting MooTools to jQuery

8 July 2010

Last night I ported some JavaScript code that used MooTools to use jQuery instead. In many ways I prefer MooTools to jQuery, but jQuery is easier to integrate in code that uses other libraries (e.g. Prototype).

Here’s a few quick hints for things you need to change if you’re doing the same.


You need a leading hash: $('#element_id')

No need for two dollars to use selectors: $('#element_id form input.special') works.

There’s a difference of approach to what happens when you use $(...): MooTools adds stuff to the DOM element. jQuery gives you a new object which wraps the element. This means you can’t just call DOM stuff on the object jQuery gives you. e.g.

$$('a.special_link').href – access the normal DOM properties

$('a.special_link').attr('href') – ask the jQuery object to access the underlying DOM element

A jQuery object can represent a list of elements, not just a single one. You can access the underlying element using index zero: $('a.special_link')[0].href


jQuery doesn’t do classes. There’s code and plugins around, or you can use a standard JavaScript approach like:

var MyClass = function(blah) {
    // this is your constructor
    this.blah = blah;
MyClass.prototype.doStuff = function(name) {
    // this is a member function
    return this.blah + name;

// instantiate and call like normal
var thing = new MyClass('hello');


Oh this one hurts. When you have a function, perhaps a callback, that you want to reference your class instance as “this“, in MooTools you use something like:

new Request.JSON({url: '...', onSuccess: function(data){

The equivalent is to use JavaScripts apply method which lets you pass an object to use for “this“. You might also want “arguments” which is an array of all arguments passed to the function. e.g.

var self = this;
$.getJSON('...', function(){return function(data){
}.apply(self, arguments)});


This is what jQuery calls bind. e.g.

$('#element_id a').bind('click', function(e){..});


Instead of MooTools’ $$('a.special').each(function(elem){...})

Try $.each($('a.special'), function(index, elem){...}). Note the first param to your function is index, not the element.


As above, try $.getJSON(url, func). You can also use $.post if it’s a POST request (seems to decode the JSON response automatically).

get and set

Instead of elem.get('href') try elem.attr('href'). Instead of elem.set('text', 'blah') there’s elem.text('blah').

That’s my braindump for now.

Filed under: JavaScript — Scott @ 10:49 am