Prototype: new Element Shortcut

February 12th, 2009

I thought I might share a little piece of code I use to create new HTML elements using Prototype. When building complex HTML fragments dynamically, always having to type "new Element" and then append the element seems like a lot of work to me. Particularly, when I just want a reference to the parent element. So I wrote this bit of code to cut out a lot of the leg work:
function $e(tag, options, children){
  if( typeof tag == 'object' ) children = options, options = tag, tag = 'div';
  var el = new Element(tag, options || {});
  if( Object.isArray(children) ) children.collect(function(e){
    if( Object.isArray(e) ){
      el.appendChild($e(e[0], e[1], e[2]));
    } else if( Object.isElement(e) ){
      el.appendChild(e);
    } else {
      el.appendChild($e(e));
    }
  });
  return el;
}
This bit of code will allow you to create complex HTML fragments like this:
$e('div', { className: 'foo' }, [ [  'span', { className: 'bar' }  ] ]);
... or ...
$e('div', { className: 'foo' }, [ $e('span', { className: 'bar' }) ]);
... or ...
$e('div', { className: 'foo' }, [ 'span' ]);
Let me know if you find this useful or have suggestion for improvement.

Leave a Reply