JasonDaly.name

PHP, Ruby, Symfony, Rails, Doctrine, MooTools. Web Development.
March 24, 2010

MooTools toElement() - Using a Class Instance to Retrieve the Related DOM Element

In MooTools the $() is used in part to ensure the element passed to $() is extended by MooTools. Clientcide points out a great tip with the native Class toElement() function.

Aside from the benefits from the use of this from outside of a class passing an instance variable to $(), I like to use toElement() in combination with $(this) from within my Class objects simply for brevity.

var someClass = new Class({

  Implement: [Options],

  options: {
    domReference: null
  },

  initialize: function(options){
    this.setOptions(options);

    // Here, $(this) will reference this.options.domReference :)
    $(this).setStyle('background-color', '#F00');
  }

  toElement: function(){
    return this.options.domReference;
  }
});

var someInstance = new someClass({
  domReference: $('some-dom-element-id')
});

Obviously the example is a little bit ridiculous just to style an element’s background red, but the point is for me it’s much cleaner having the option to write

$(this).setStyle('background-color', '#F00');

than

this.options.domReference.setStyle('background-color', '#F00');

Tags: mootools javascript code tips