Lunes ~ Marzo 3, 2008

createElements() una función para ahorrarte mucho código

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({…});

Quizas te pueda interesar

5 Responses to “createElements() una función para ahorrarte mucho código

Pingback

Comentarios

1

Tremendo… MUCHAS GRACIAS!!

# David -- 03/03/08 - 9:14 pm Responder
2

De mucha ayuda, a mi personalmente me gusta mas

add(tag name, {…});

pero bueno, solo me queda una duda…

if ( args.style ) {

eso da error si no esta definido style… lo mismo con childrens…

# Manolo -- 04/03/08 - 2:29 pm Responder

Deja un comentarioTop

Me reservo el derecho de eliminar y/o modificar los comentarios que contengan lenguaje inapropiado, spam u otras conductas no apropiadas en una comunidad civilizada. Si tu comentario no aparece, puede ser que akismet lo haya capturado, cada día lo reviso y lo coloco en su lugar. Siento las molestias.

Esta web se encuentra sobre la licencia Creative Commons (Reconocimiento - Compartir igual) / Politicas de uso

Cerrar
Enviar por Correo