Knowing several languages but rusty with javascript, I know how there can be pitfalls in learning bad habits or coming up with convoluted, less than optimal solutions that would make more sense in other languages, almost abusing the language rather than working off of what it does best. So I am wondering if anything is unoptimal with the code below. The xml file is being read in; the code expects a 'featurelist' tag where 'ideas' and 'chapters' are organised under other chapters (except the top-level ones). Right now the code doesn't acknowledge the idea tags, it just tries to render the chapters in a html 'table of contents' in a tree-like organisation. The outputted html is correct, but I inserted some extra code to skip tags of the wrong id. This is the particular hot-spot where I'm wondering if better solutions are available, perhaps built-in rather than writing it 'by hand'.
<script type="text/javascript">function processxml(xmldoc) { i = 0; root = xmldoc.getElementsByTagName("featurelist")[0]; el = root.getElementsByTagName("chapter")[0]; /* Initiate contents */ str = '<ul id="contents">'; while(el && el != root) { if(c=el.getAttributeNode("htmlclass")) str += '<div id="' + c.value + '">'; str += "<li>" + el.getAttribute("title") +"</li>"; if((els = el.getElementsByTagName("chapter")).length) { /* Has child chapters */ str += "<ul>"; el = els[0]; continue; } esc = 0; while(!esc) { save = el; while((el = el.nextSibling) && el.nodeName != "chapter") ; if(!el) { /* No next sibling */ str += "</ul>"; el = save; while((el = el.parentNode) && el.nodeName != "chapter") ; if(!el) /* No parent */ break; else /* Found parent, look again for sibling */ continue; } else { /* We have next sibling */ if(c) str += "</div>"; esc = 1; } } } /* Terminate contents */ str += "</ul>"; alert(str);// document.write(str); document.body.innerHTML = str;}
Or have I done everything as well as it could be done?