No Mod Required

Playing Around With ECMAScript for XML (e4x)

As I mentioned I was reading John Resig’s Pro JavaScript Techniques recently (I actually finished it today.) The last chapter deals with the future of the language, and goes into a few different JS related technologies on the horizon- the <canvas> element, Comet, etc. One technology featured I’d never actually played around with was ECMAScript for XML (E4X.) Reading the sample code, I realized it could potentially be really useful, so I decided to take it for a little spin this afternoon, just to get a feel for what it might be like to work with. I came up with the following…

Here’s some sample code:



function e4xDemo() {
      //create a new div
      var newDiv = <div/>;
      //append an H1 with some text 
      newDiv.h1 = "This is an e4x generated header";
      //give the div an ID
      newDiv.@id= "e4x";
      //append an H2 with some text
      newDiv.h2 = "let's create a more complicated structure"
      //append a whole slew of divs and a paragraph
      //this feels like it could be very powerful
      newDiv.div.div.div.div.p = "isn't this kind of cool?";
      //add another paragraph
      newDiv.p = "let's add in an image";
      //if E4X was widely supported
      //I'd use this pattern all the time
      newDiv.p.img.@src="http://media.drunkenfist.com/304/wp-content/uploads/2008/01/graffiti-letter-i.thumbnail.jpg";
      //E4X creates a variable of type XML
      //Which is basically just a string full XML
      //so we use innerHTML to jam it into the doc
      $("contents").innerHTML=newDiv;
      //Then we spit out the full text of the variable into a PRE
      $("view-source").appendChild(document.createTextNode(newDiv));
      //use the .. operator that searches all child nodes of a certain type
      $("dot-dot-p").appendChild(document.createTextNode(newDiv..p));
      return false;
  };


And here it is in action (Firefox only):

First impression? It wouldn’t completely replace strings+innerHTML or the proper DOM methods like createElement or appendChild, but E4X would come in handy in a lot of situations and if it were more widely supported it would immediately get some use. For example, I’d definitely use the var newImg = img.@src = "path/to/image" pattern all the time when creating images on the fly (it’s just so direct) and I’m betting I’d use <div/> and div.@id in place of some of the longer, tougher- to- read strings I drop into HTML docs with innerHTML.

I’m going to continue to experiment with it. I’m going to try to rewrite some of my existing code using E4X, so we’ll see what shakes out with the tinkering.

Leave a Reply

Note: Wrap all of your code blocks in <code>...</code> and replace < and > with &lt; and &gt;, respectively.