Notice This is a beta feature offered by Google. Also this is automatic translation, which means the results are often inacurate and/or hilarious. Enjoy.

ARCHIVES / RSS
Blog

$E method for prototype.js

h3  ~  1 Aug 2007, 02:27  –  post a comment

While writing a small JavaScript application I had to generate HTML with javascript. I used Scriptaculous's Builder.js, but I had that feeling that it was too much for nothing and I always try to avoid depedencies when I can..

So I came up with $E, a quick and dirty way to create HTML DOM elements, here's the code:

$E = function() { // args: type, innerHTML, parentNode
	if (arguments[0]) {
		node = document.createElement(arguments[0]);
		Element.extend(node);
		if (arguments[1]) node.innerHTML = arguments[1];
		if (arguments[2]) $(arguments[2]).appendChild(node);
		return node;
	}
	else throw('Error: $E expect at least 1 arguments.');
}

// basic usage:

breaklineElement = $E('br');

By itself it's a bit trivial, but with methods chaining the real fun begins:

paragraph = $E('p').innerHTML = 'Hello world !';

myDiv = $E('div').setStyle({
    background:'#c30;',
    color:'#fff',
    height:'100px',
    width:'100px'
}).innerHTML = 'Hello world :)';

It's crazy how 10 lines of JavaScript can make your day.

post a comment Comments

no comments :|

Copyrighted stuff .. u know.