Element Creation Shortcut in MooTools

Lately, I’ve been bothered about the amount of typing and lines required to create a simple element in MooTools.

var curly = new Element('div', {
  id : 'curly',
  'class' : 'stooge'

In jQuery, you’re given the convenience of writing HTML into the jQuery function —

var $curly = $('<div id="curly" class="stooge" />');

To me, this is quick and easy, but it’s very unnatural typing HTML into JavaScript and I’ve seen this convenience become quickly (and horrifyingly) abused.1 MooTools deserves something cleaner and cooler, so today I realized I could use a limited selector to create an element. I liked that idea very much.

var curly = $E('div#curly.stooge');

(update: Apparently I’m not the first to think of this. A couple weeks before I wrote this post, this commit was made to MooTools 2.0 adding this capability to new Element. The idea came from Thomas Aylott. I am so happy to see this become a part of the next version of MooTools!)

I know, $E was used in MooTools 1.1 for finding an element by a selector with an optional filter, but that is longer the case in MooTools 1.2. Besides, $A and $H are used for to create a new array or hash, respectively, so it seems only natural to me to use $E for creating an element. If you don’t like my reasoning, then you can change the name and I promise I won’t hunt you down.

function $E(tag, props) {
  if (typeof props == 'string')
    props = { style : props };
  if (typeof tag == 'string') {
    var id = tag.match(/#([\w-]+)/);
    var classes = tag.match(/(?:\.[\w-]+)+/);
    tag = tag.replace(/[#.].*/, '');
    props = props || {};
    if (id) props.id = id[1];
    if (classes) props['class'] = classes[0].replace(/\./g, ' ');
  return new Element(tag || 'div', props);

(edit: a style string can now optionally be passed into props, further updates will be on GitHub here)

With this new magical utility function, you can quickly and easily create elements with an optional id and any number of classes, along with additional properties passed into the optional second argument. In fact, you can omit a tag and it’ll default to a <div>.

var moe = $E('#moe.stooge.leader', {...});

I’m pretty excited about using this new shortcut, and I hope you are too. Please shout out in the comments if you find it useful or have any tweaks.

Note to plugin developers: If you decide to use this, please place it inside of a closure so it doesn’t override someone else’s $E function. I saw this suggestion on the MooTools Twitter2 so I can imagine this becoming a problem —

$E = document.getElement.bind(document);

1 Some even prefer to use double quotes and then escape all the attribute quotes. Ughh!

2 My last post on custom events was linked there!

About Me

I'm Scott Kyle, a MooTools developer and Apple addict. You can follow me on Twitter, fork me on GitHub, and check out some of my work on my portfolio.