Uno de los problemas con los que nos encontramos con Javascript es la cantidad de líneas de código que hemos de escribir para trabajar con DOM, pese a haber frameworks que se encargan de que nuestro código sea más ligero, no siempre podemos disponer de este lujo.
La creación de elementos es algo bastante laborioso, y por ello los frameworks ponen especial empeño en mejorar este punto ya que es algo que cada vez más usamos en nuestros scripts. createElements() es una función que facilita esta tarea sin necesidad de depender de un framework, 30 líneas que te ahorrarán 30.000.
La función
function createElements( args ) {
var el;
if( typeof(args) == "string" ) {
el = document.createTextNode(args);
} else if ( typeof(args) == "object" ) {
el = document.createElement( args.tag );
if ( args.attributes ) {
for ( i in args.attributes ) {
el.setAttribute(i, args.attributes[i]);
}
}
if ( args.style ) {
for ( i in args.style ) {
el.style[i] = args.style[i];
}
}
if ( args.children ) {
for ( var i = 0; i < args.children.length; i++ ) {
el.appendChild( createElements( args.children[i] ) );
}
}
}
return el;
}
Modo de empleo
var node = createElements({
tag: "div",
attributes: {
id: "google_link"
},
children: [
{
tag: "a",
attributes: {
href: "http://www.google.com"
},
style: {
textDecoration: "none",
fontWeight: "bold"
},
children: [
{
tag: "img",
attributes: {
src: "http://www.google.com/intl/en_ALL/images/logo.gif",
alt: "Google!",
title: "Google!",
border: "0"
},
style: {
width: "200px",
height: "200px"
}
},
{
tag: "br"
},
"Click here to go to Google!"
]
}
]
});
document.body.appendChild(node);
Actualización
Una pequeña modificación, para hacerlo más cómodo.
HTMLElement.prototype.add = function(args) {
var el;
if( typeof(args) == "string" ) {
el = document.createTextNode(args);
} else if ( typeof(args) == "object" ) {
el = document.createElement( args.tag );
if ( args.attributes ) {
for ( i in args.attributes ) {
el.setAttribute(i, args.attributes[i]);
}
}
if ( args.style ) {
for ( i in args.style ) {
el.style[i] = args.style[i];
}
}
if ( args.children ) {
for ( var i = 0; i < args.children.length; i++ ) {
el.appendChild( this.add( args.children[i] ) );
}
}
}
this.appendChild(el);
}
//USO:
$("header").add({...});
2 comentarios, 4 referencias
+
#