Looking for XML elements in Javascript with e4x

If you are manipulating XML in Javascript then E4X is one of the options available to you. The problem is that the documentation is a little thin and the examples only show you how to find things that definitely exist. So here’s some help in trying to see if elements exist or not.

In this example, I’m processing DITA and trying to find the “title” of the document. This can be in a variety of locations in DITA and can be a <title> in a topic, concept, etc. or a <mainbooktitle> element in a bookmap. So how do you see if you have a mainbooktitle in e4x?

var concept = new XML("...my dita concept xml...");
var mainbooktitle = concept..mainbooktitle;
if (mainbooktitle.length() > 0) {
    // we have a mainbooktitle

The concept..mainbooktitle construct finds all children elements in the document named mainbooktitle and returns them in an XMLList. Crucially the documentation does not tell you that an XMLList is always returned and can either be:

  1. A list of length zero meaning no elements named mainbooktitle were found
  2. A list of length one meaning only one element was found. When this happens, you can refer to the item as if it were not in a list. For example, to get the id attribute you could just say mainbooktitle.@id instead of mainbooktitle[0].@id.
  3. A list of length greater than one. You should then use a for each loop or access items by index like this mainbooktitle[1].@id

I hope this saves somebody some time because I had to figure it out by trial and error!

YUI Carousel Only Showing One Row When I Want Two!

I fought with this issue all afternoon. I was setting up my carousel like this:

var carousel = new YAHOO.widget.Carousel("container");
carousel.set("numVisible", [5,2]);

But no matter how hard I tried. I couldn’t get it to show me more than one row. Over and over I fiddled with widths and heights and borders and padding but no luck. Finally, I took the example from the YUI Library Example Page and copied and pasted the HTML line by line into my page. When I got finished, the example was broken too!¬† So, what to do?

I wandered down to my javascript and compared it to the example one. The example passed in the columns and rows during the creation of the Carousel object and I was setting the variable right after I created it. Aha. So, I changed my two lines of code to this:

carousel = new YAHOO.widget.Carousel("container", {
// specify number of columns and number of rows
numVisible: [6, 4]

And everything is now working. Time for a pint.