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
    fetch API

    One of the worst kept secrets about AJAX on the web is that the underlying API for it, XMLHttpRequest, wasn't really made for what we've been using it for.  We've done well to create elegant APIs around XHR but we know we can do better.  Our effort to...

  • By
    6 Things You Didn’t Know About Firefox OS

    Firefox OS is all over the tech news and for good reason:  Mozilla's finally given web developers the platform that they need to create apps the way they've been creating them for years -- with CSS, HTML, and JavaScript.  Firefox OS has been rapidly improving...

Incredible Demos

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!