Generar DOM con JavaScript mas facilmente

02:30PM sep 27, 2005 in category General by Alberto Gimeno

Hola. Una de las bases de AJAX es la generación de contenido dinámicamente a partir de información de una petición HTTP. Esta generación del contenido se hace mediante DOM. Se van creando nodos y añadiéndose a la página.

No soy un gurú del tema, pero veo que es una tarea bastante tediosa. Un ejemplo de cómo crear un párrafo e insertarlo en cierto nodo ya existente...

<div id="lugar_en_el_que_insertar">
</div>

<script language="javascript">
var parrafo = document.createElement("p");
var texto = document.createTextNode("texto...");
parrafo.appendChild(texto);

document.getElementById("lugar_en_el_que_insertar").appendChild(parrafo);
</script>

Se me ha ocurrido que puede ser de ayuda que dado el HTML un programilla te genere todo el javascript necesario para generar ese HTML. Por ejemplo dado este HTML...

<p> visita <a href='http://weblogs.javahispano.org/page/gimenete'>mi weblog</a></p>

...te genere...

var p0 = document.createElement("p");
p0.appendChild(document.createTextNode(" visita "));

var a1 = document.createElement("a");
a1.setAttribute("href", "http://weblogs.javahispano.org/page/gimenete");
a1.appendChild(document.createTextNode("mi weblog"));
p0.appendChild(a1);

document.getElementById("id_del_elemento_donde_se_quiere_insertar").appendChild(p0);

Para probarlo nada más que hacer algo como lo siguiente...

<div id="lugar_en_el_que_insertar">
</div>

<script language="javascript">
var p0 = document.createElement("p");
p0.appendChild(document.createTextNode(" visita "));

var a1 = document.createElement("a");
a1.setAttribute("href", "http://weblogs.javahispano.org/page/gimenete");
a1.appendChild(document.createTextNode("mi weblog"));
p0.appendChild(a1);

document.getElementById("lugar_en_el_que_insertar").appendChild(p0);
</script>

Pues bueno, he hecho esta aplicación usando jDom. Este es el código

package net.gimenete.html2js;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Iterator;

import org.jdom.Attribute;
import org.jdom.Comment;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Text;
import org.jdom.input.SAXBuilder;

public class Html2JavaScriptApp {
	
	private int index;
	private String first;
	private Writer writer;

	public static void main(String[] args) {
		SAXBuilder builder = new SAXBuilder();
		builder.setValidation(false);
		builder.setIgnoringElementContentWhitespace(true);
		Document document = null;
		try {
			document = builder.build(new InputStreamReader(System.in));
		} catch (JDOMException e) {
			System.err.println("error en el formato de entrada. no es xml "+e);
			System.exit(0);
		} catch (IOException e) {
			System.err.println("error al leer del canal de entrada "+e);
			System.exit(0);
		}
		
		Html2JavaScriptApp app = new Html2JavaScriptApp();
		PrintWriter writer = new PrintWriter(System.out);
		String id = null;
		if(args.length > 0)
			id = args[0];
		try {
			app.generateDocument(writer, document, id);
		} catch (IOException e) {
			System.err.println("error generando el javascript "+e);
			System.exit(0);
		}
		writer.flush();
	}
	
	public void generateDocument(Writer writer, Document document, String id) throws IOException {
		index = 0;
		first = null;
		this.writer = writer;
		generateElement(document.getRootElement(), null);
		if(first != null && id != null) {
			writer.write("document.getElementById(\""+id+"\").appendChild("+first+");\n");
		}
	}
	
	private void generateElement(Element element, String parentName) throws IOException {
		String name = element.getAttributeValue("id");
		if(name == null) {
			name = element.getName()+index;
			index++;
		}
		if(first == null)
			first = name;
		writer.write("/* ["+element.getName());
		for (Iterator iter = element.getAttributes().iterator(); iter.hasNext();) {
			Attribute attr = (Attribute) iter.next();
			writer.write(" "+attr.getName()+"=\""+attr.getValue()+"\"");
		}
		writer.write("] */\n");
		writer.write("var "+name+" = document.createElement(\""+element.getName()+"\");\n");
		for (Iterator iter = element.getAttributes().iterator(); iter.hasNext();) {
			Attribute attr = (Attribute) iter.next();
			writer.write(name+".setAttribute(\""+attr.getName()+"\", \""+attr.getValue()+"\");\n");
		}
		
		for (Iterator iter = element.getContent().iterator(); iter.hasNext();) {
			Object child = iter.next();
			if(child instanceof Element)
				generateElement((Element) child, name);
			else if(child instanceof Text)
				generateText((Text) child, name);
			else if(child instanceof Comment)
				generateComment((Comment) child);
		}
		if(parentName != null) {
			writer.write(parentName+".appendChild("+name+");\n");
		}
		writer.write("\n");
	}

	private void generateComment(Comment comment) throws IOException {
		writer.write("/* "+comment.getText()+" */\n");
	}

	private void generateText(Text text, String parentName) throws IOException {
		String txt = text.getText().replaceAll("\r", " ").replaceAll("\n", " ");
		writer.write(parentName+".appendChild(document.createTextNode(\""+txt+"\"));\n");
	}

}

Y así es como se usa...

echo "<p> visita <a href='http://weblogs.javahispano.org/page/gimenete'>mi weblog</a></p>" | java net.gimenete.html2js.Html2JavaScriptApp id_del_elemento_donde_se_quiere_insertar_el_arbol

Es decir lee de la entrada estándar y escribe en la salida estándar. En el ejemplo anterior usamos la salida de "echo" como entrada. También podemos leer de un fichero...

java net.gimenete.html2js.Html2JavaScriptApp < /Users/gimenete/test.xml

El único parámetro que necesita el programa es opcional. Indica el "id" del elemento en el que se debe insertar todo el DOM generado. En el segundo ejemplo como se ve no lo he usado.

Sugerencias? Comenarios?

Comentarios[82]

Comentarios:

document.getElementById('lugar_en_el_que_insertar').innerHTML = "<div class='AlertGood'>stuff</div>"

Enviado por Aitor Garcia en septiembre 28, 2005 a las 07:08 AM GMT+01:00 #

Pues vaya paja mental me he cascao entonces xD

Enviado por gimenete en septiembre 28, 2005 a las 01:32 PM GMT+01:00 #

No te preocupes. Estas pequeñas practicas nunca vienen mal si tienes un poco de tiempo libre. Entrenan el cerebro.

Enviado por Aitor Garcia en septiembre 29, 2005 a las 07:27 AM GMT+01:00 #

[Trackback] yovatblnblg wcxzmbgg yxhebpak

Enviado por tvpspwlgi en julio 10, 2006 a las 11:38 AM GMT+01:00 #

[Trackback] vdstsd ydsyr yty ydsy sy bjghjkf ghfg h f

Enviado por vtdrsbtdtdsb en julio 10, 2006 a las 06:25 PM GMT+01:00 #

[Trackback] He followed this post with an (implicit, naturally) apology for his failure to follow one of Grice?s maxims of manner.

Enviado por hxderytyevo en julio 11, 2006 a las 07:21 AM GMT+01:00 #

[Trackback] yvrttny yre tryfghgj jytjt rtrtwretretrytyt u gretgry

Enviado por bcfgsbvbvdfgkdgh en julio 11, 2006 a las 10:11 AM GMT+01:00 #

[Trackback] isdciayriq hhexmdea vrdawure

Enviado por rghbgsnk en julio 12, 2006 a las 10:28 PM GMT+01:00 #

[Trackback] fvytrv ytryfrtuyiunyy ijuy irgtu

Enviado por vbtrhcrt htrvurye en julio 12, 2006 a las 11:10 PM GMT+01:00 #

[Trackback] vdsbyrtys bfcnsfygd fgrugfxhfs jwufs fhsif syfs hfjk sdfhsdifiuhf

Enviado por bxefgtecbwu en julio 13, 2006 a las 04:37 AM GMT+01:00 #

[Trackback] Neal Ascherson just wrote in the Guardian about how the nation turned to talk

Enviado por bxetwyv en julio 13, 2006 a las 07:00 AM GMT+01:00 #

[Trackback] Best porn movies archive. Free FTP download.

Enviado por Porn movies en julio 14, 2006 a las 04:41 PM GMT+01:00 #

[Trackback] Best sex picture amateur archive. http://www.sexwwwinfo.com - amateur picture daily upload.

Enviado por free sex en julio 15, 2006 a las 04:55 PM GMT+01:00 #

[Trackback] This is the best I could do by way of finding an example of work by Klaus Meyer. it?s called Chance and is one of a series of wood and lino cuts he did to illustrate poems by Goethe.

Enviado por lortab en julio 15, 2006 a las 08:41 PM GMT+01:00 #

[Trackback] He followed this post with an (implicit, naturally) apology for his failure to follow one of Grice?s maxims of manner.

Enviado por lortab en julio 16, 2006 a las 03:37 AM GMT+01:00 #

[Trackback] As such, I have a present for you. Straight from Kirby Ferguson himself, his new video for the Wet Spot?s classic hit, ?Do You Take It??

Enviado por diet-online-pill en julio 16, 2006 a las 06:35 AM GMT+01:00 #

[Trackback] I?ve decided not to tell him what he?s missing, but I will mention that there?s a link there to get your war on which is where I keep myself up to date with current US thinking.

Enviado por diet-hoodia en julio 16, 2006 a las 02:13 PM GMT+01:00 #

[Trackback] He followed this post with an (implicit, naturally) apology for his failure to follow one of Grice?s maxims of manner.

Enviado por lortab-side-effects en julio 16, 2006 a las 07:36 PM GMT+01:00 #

[Trackback] I?ve decided not to tell him what he?s missing, but I will mention that there?s a link there to get your war on which is where I keep myself up to date with current US thinking.

Enviado por lortab en julio 17, 2006 a las 03:06 AM GMT+01:00 #

[Trackback] But things are improving. Just got a message from LINGUIST telling me about the latest issue of Snippets, an online journal publishing squibs on syntax and semantics in pdf format.

Enviado por Amateur boxing en julio 17, 2006 a las 06:18 AM GMT+01:00 #

[Trackback] I do love Favreau (and Vince Vaughn, for that matter) in that movie... not to mention Heather Graham.

Enviado por Asian sex en julio 17, 2006 a las 09:26 AM GMT+01:00 #

[Trackback] Free amateur sex blog. Free movies Free pics

Enviado por Amateur sex en julio 17, 2006 a las 12:55 PM GMT+01:00 #

[Trackback] The new mode might sound a bit strange, even bizarre. But that ought to tell us something ? when candor seems weird and preposterous claims seem quite normal.

Enviado por diet-pill en julio 17, 2006 a las 04:53 PM GMT+01:00 #

[Trackback] Free Swingers Sex Blog. Free Swingers Movies. Free Swingers Dating.

Enviado por Swingers Online en julio 18, 2006 a las 12:33 AM GMT+01:00 #

[Trackback] And if you want to worry about whether Osama?s got nukes, try here.

Enviado por sex blog en julio 18, 2006 a las 07:27 AM GMT+01:00 #

[Trackback] Then He slapped my ass and ordered me under the desk. It was then that I knew that this time it was going to push even my whorish limits on performing as His sex slave.

Enviado por Blowjob sex en julio 18, 2006 a las 01:32 PM GMT+01:00 #

[Trackback] These pics of nude lesbian girls is targeted to an adult audience who likes to view porn

Enviado por Free Lesbian Sex en julio 19, 2006 a las 05:26 AM GMT+01:00 #

[Trackback] Sex Toys Dildos Sex Aids Sex Toys Online

Enviado por Free Sex en julio 19, 2006 a las 06:54 AM GMT+01:00 #

[Trackback] Free Web Hosting is the Internet\'s premiere free website hosting service featuring 100 MB of storage, 2GB file transfer, online file manager and more!

Enviado por Free Hosting en julio 19, 2006 a las 08:47 AM GMT+01:00 #

[Trackback] This is about how some of Godspeed You! Black Emperor were held for questioning as suspected terrorists in Oklahoma recently. They clearly forgot their ?we are not terrorists? bumper stickers.

Enviado por Interracial Sex en julio 19, 2006 a las 10:39 AM GMT+01:00 #

[Trackback] Buy Cialis at $1.12 Per Dose - Low Prices

Enviado por Buy Cialis en julio 19, 2006 a las 12:36 PM GMT+01:00 #

[Trackback] Dick Hudson, in absentia, on language teaching

Enviado por Free XXX en julio 19, 2006 a las 02:41 PM GMT+01:00 #

[Trackback] \"Would you jack off to that piece of shit?\"

Enviado por Penis sex en julio 19, 2006 a las 07:12 PM GMT+01:00 #

[Trackback] Plus, I\'m supposed to be the quietly accepting slavegirl right? Whether it\'s locking me in a closet or sending me off to work or expecting me to function without Him, I\'m to just obey.

Enviado por Free Pussy en julio 20, 2006 a las 04:41 AM GMT+01:00 #

[Trackback] Anal Sex Archive Galleries Anal Sex Porn Links

Enviado por Anal Sex en julio 20, 2006 a las 06:23 AM GMT+01:00 #

[Trackback] Online Dating Services

Enviado por Online Dating Services en julio 20, 2006 a las 07:22 AM GMT+01:00 #

[Trackback] Free Asian sex & porn

Enviado por Asian Sex en julio 20, 2006 a las 09:18 AM GMT+01:00 #

[Trackback] William Safire has just been picked on by a blog with a name that keeps changing. Not too harshly, though. The comment is William Safire, you annoy me.

Enviado por best-diet-pill en julio 20, 2006 a las 10:23 AM GMT+01:00 #

[Trackback] They\'d worked on it, exhaustively, for so long. He\'d rather go back to plumbing in Chicago. And a couple hours later, it was clear that was never going to happen!

Enviado por Asian model Sex en julio 20, 2006 a las 11:22 AM GMT+01:00 #

[Trackback] BlogThis!The thoughts, and musings of a woman on a quest to explore her submission. \"Life\'s a dance, you learn as you go. Sometimes you lead, sometimes you follow........\"

Enviado por Hardcore sex en julio 20, 2006 a las 12:29 PM GMT+01:00 #

[Trackback] Big Bonus Casino: Best casino advice since 2002!

Enviado por Las Vegas Casino en julio 20, 2006 a las 10:34 PM GMT+01:00 #

[Trackback] (I know I know, go back and do it later. I KNOW.)

Enviado por Gay sex en julio 21, 2006 a las 04:23 AM GMT+01:00 #

[Trackback] I may not always submit gracefully, but I always submit.

Enviado por Blonde Sex en julio 21, 2006 a las 05:59 AM GMT+01:00 #

[Trackback] Free Porn- teen sex videos, free amateur porn pictures, teens suck

Enviado por Teen Sex en julio 21, 2006 a las 07:35 AM GMT+01:00 #

[Trackback] Then He slapped my ass and ordered me under the desk. It was then that I knew that this time it was going to push even my whorish limits on performing as His sex slave.

Enviado por Swingers sex en julio 21, 2006 a las 09:12 AM GMT+01:00 #

[Trackback] But here is where you can ?do the math? (actually, where someone did the math a long time ago, as you can tell by the fact that none of the images work any more)

Enviado por Russian-women en julio 21, 2006 a las 01:11 PM GMT+01:00 #

[Trackback] Hope they?ve done a statistical significance test on that.

Enviado por Teen Sex blog en julio 21, 2006 a las 04:34 PM GMT+01:00 #

[Trackback] It\'s always been all or nothing for me. Always.

Enviado por Dildo Sex en julio 21, 2006 a las 06:47 PM GMT+01:00 #

[Trackback] Never fear Englishman, I do trust...it is just on levels and to degrees and the journey there is much more important to me than the final outcome is for some reason.

Enviado por virtual casino en julio 21, 2006 a las 09:16 PM GMT+01:00 #

[Trackback] Renee pointed me to this article about the similarities between historical linguistics and science fiction.

Enviado por casino on line en julio 21, 2006 a las 11:25 PM GMT+01:00 #

[Trackback] PPS In fact, I received a copy of the ?email you sent? which means Brian put my email address in the box (yes, I can work out who he is)

Enviado por xpoenpba en julio 22, 2006 a las 04:59 AM GMT+01:00 #

[Trackback] We?re sorry this didn?t work out as we?d hoped.

Enviado por pxrnindgs en julio 22, 2006 a las 09:47 AM GMT+01:00 #

[Trackback] Clemmie came out with us on Sunday, but the poor wee thing was suffering from a bit of a cold. Nicki came and rescued her at the end of the day.

Enviado por dating sex en julio 22, 2006 a las 12:10 PM GMT+01:00 #

[Trackback] "This is what will happen when you get OOOOOUUUUWWWLLLLDDDD."

Enviado por bviszazcg en julio 22, 2006 a las 03:34 PM GMT+01:00 #

[Trackback] btw, does anyone know the story behind the sign we saw out in Essex which points the way to the Secret Nuclear Bunker? It?s just one more option on a big green roundabout directions sign.

Enviado por dvvogzvshw en julio 22, 2006 a las 10:12 PM GMT+01:00 #

[Trackback] He turned to me with big eyes and said, "You are so beautiful!" I blushed & thanked him.

Enviado por pzhojmqnew en julio 23, 2006 a las 03:51 AM GMT+01:00 #

[Trackback] Ohna?s at work, six kids are running riot in my house, I?ve just about got the lunches together. Someone?s at the door. Oops, must dash. We?ve got a war to stop.

Enviado por dirbaog en julio 23, 2006 a las 05:19 AM GMT+01:00 #

[Trackback] fhsdgfhd fsdgfsdg udgphdfgh gdfgfd

Enviado por swingers en julio 23, 2006 a las 09:25 PM GMT+01:00 #

[Trackback] fhsdgfhd fsdgfsdg udgphdfgh gdfgfd

Enviado por swingers en julio 23, 2006 a las 09:25 PM GMT+01:00 #

[Trackback] Poopers, pleasure palace or exit only, please?

Enviado por Free sex en julio 24, 2006 a las 04:20 AM GMT+01:00 #

[Trackback] I did, but I fucked it up, and my sister Gideon was too busy to fix it. I don't know anything about HTML.

Enviado por szsejpds en julio 24, 2006 a las 07:06 AM GMT+01:00 #

[Trackback] Frivolous bastardisation of our punctuation is one of the key witnesses to the current decline of our wonderful nation.?

Enviado por lokkudavge en julio 24, 2006 a las 10:08 AM GMT+01:00 #

[Trackback] "The only award that actually makes a difference in sales."

Enviado por yntfjno en julio 24, 2006 a las 12:59 PM GMT+01:00 #

[Trackback] Typically, Master is not aroused during punishment. However, He is a sadist, He was hurting me, I was naked and squirming and moaning. He wanted to fuck.

Enviado por ymmdhnztylk en julio 24, 2006 a las 04:47 PM GMT+01:00 #

[Trackback] So I never did get around to doing Master's taxes yesterday. (I did them today though, done, finished.) I could claim subdrop yesterday but it wasn't really. I just felt like a slug. So I did nothing.

Enviado por fbtvdovjw en julio 24, 2006 a las 07:18 PM GMT+01:00 #

[Trackback] starts in a few days. My lawyer tells me I face staturory rape charges

Enviado por Amateur en julio 26, 2006 a las 10:31 PM GMT+01:00 #

[Trackback] Jennifer reached down to touch it. She ran one finger over the firm, hard surface. Brandon leaned over and growled against her skin.

Enviado por swinger party en agosto 04, 2006 a las 12:14 AM GMT+01:00 #

[Trackback] When generic name for xanax sideffects ...

Enviado por xanax online en agosto 04, 2006 a las 10:39 AM GMT+01:00 #

[Trackback] jkshfdjsh fhfsuidafuisd f gfweogfiywegf

Enviado por Phentermine en agosto 05, 2006 a las 09:41 AM GMT+01:00 #

[Trackback] Dick Hudson, in absentia, on language teaching

Enviado por Pregnant Sex en agosto 05, 2006 a las 02:12 PM GMT+01:00 #

[Trackback] Cheap valium on Friday, 21 July 2006, at 3:46 p. cheap valium Buy Alprazolam -- cheap valium Sunday, 9 July 2006.

Enviado por valium en agosto 06, 2006 a las 04:55 AM GMT+01:00 #

[Trackback] When we had two million on the streets we should have rioted for peace and brought down the government?

Enviado por diazepam en agosto 06, 2006 a las 08:03 AM GMT+01:00 #

[Trackback] 10cbd65254a21b18c8fc2d415fe13ce6<a href="http://10cbd65254a2.info">10cbd65254a2</a>

Enviado por 10cbd65254 en septiembre 18, 2006 a las 07:26 AM GMT+01:00 #

[Trackback]

Enviado por hydrocodone en septiembre 18, 2006 a las 09:21 AM GMT+01:00 #

[Trackback]

Enviado por buy hydrocodone online en septiembre 18, 2006 a las 09:27 AM GMT+01:00 #

[Trackback]

Enviado por xanax effect en septiembre 18, 2006 a las 09:47 AM GMT+01:00 #

[Trackback]

Enviado por xanax no prescription en septiembre 18, 2006 a las 09:52 AM GMT+01:00 #

[Trackback]

Enviado por cheap xanax en septiembre 18, 2006 a las 09:55 AM GMT+01:00 #

[Trackback]

Enviado por buy cialis en septiembre 18, 2006 a las 10:01 AM GMT+01:00 #

[Trackback]

Enviado por cheapest cialis en septiembre 18, 2006 a las 10:11 AM GMT+01:00 #

[Trackback]

Enviado por buy cialis online en septiembre 18, 2006 a las 10:16 AM GMT+01:00 #

[Trackback]

Enviado por cialis viagra en septiembre 18, 2006 a las 10:30 AM GMT+01:00 #

Enviar un comentario:
  • Sintaxis HTML: Deshabilitado