MooTools Tip: Class.toElement

By  on  

Many of you may not know of a feature that's baked into MooTools' Class internals: Class.toElement. Class.toElement allows you to pass the $ (or document.id) method an instance of your class and the instance will be treated as an element.

The MooTools Class.toElement Usage

/* baking into the class */
var myClass = new Class({
	initialize: function(container,options) {
		this.container = $(container);
	},
	// .. lots more methods //
	toElement: function() {
		return this.container;
	}
});

/* usage */
var mc = new MyClass('wrapper');
$(mc).fade('out'); //fades the container out

This isn't a groundbreaking piece of code but it's just another example of the flexibility that MooTools affords its developers. Happy coding!

Recent Features

  • By
    An Interview with Eric Meyer

    Your early CSS books were instrumental in pushing my love for front end technologies. What was it about CSS that you fell in love with and drove you to write about it? At first blush, it was the simplicity of it as compared to the table-and-spacer...

  • By
    Responsive Images: The Ultimate Guide

    Chances are that any Web designers using our Ghostlab browser testing app, which allows seamless testing across all devices simultaneously, will have worked with responsive design in some shape or form. And as today's websites and devices become ever more varied, a plethora of responsive images...

Incredible Demos

  • By
    MooTools Zebra Tables Plugin

    Tabular data can oftentimes be boring, but it doesn't need to look that way! With a small MooTools class, I can make tabular data extremely easy to read by implementing "zebra" tables -- tables with alternating row background colors. The CSS The above CSS is extremely basic.

  • By
    Reverse Element Order with CSS Flexbox

    CSS is becoming more and more powerful these days, almost to the point where the order of HTML elements output to the page no longer matters from a display standpoint -- CSS lets you do so much that almost any layout, large or small, is possible.  Semantics...

Discussion

  1. Haven’t noticed this wonderful tiny yet so useful method before. Thanks for bringing this up :)

  2. jeremy

    i was actually just reading about this today.

    it seems often times the method is used to create the element that gets returned as well, in which case its important to make sure the method doesn’t re-define the element it returns.

    toElement: function() {
    if (this.element) return this element;
    return this.element = new Element(...);
    }
    
  3. Hey, that’s a useful thing! Didn’t know this before, THX for sharing!

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!