views:

30

answers:

1

I am writing a bit of code that appends my site nav with and extra ul that gives a description about where that link takes you. I need to use our CMS's built in Nav structure so appending via jQuery was the best solution, and XML makes the data easier to manage. My question is this: is there a more efficient way to write out the js? What I have so far is this:

$(document).ready(function()
{
 $.ajax({
  type: "GET",
  url: "/js/sitenav.xml",
  dataType: "xml",
  success: function  parseXml(xml) {
  // WORK
   $(xml).find("CaseStudies").each(function()
    {
     $("li#case_studies").append('<ul><li>' + $(this).find("NavImage").text() + $(this).find("NavHeader").text() + $(this).find("NavDescription").text() + $(this).find("NavLink").text()  + "</li></ul>");
    });
   };
 });
});

and the xml structure resembles this:

<SiteNav>
 <Work>
        <CaseStudies>
            <NavImage></NavImage>
         <NavHeader></NavHeader>
         <NavDescription></NavDescription>
         <NavLink></NavLink>
        </CaseStudies>
    </Work>
</SiteNav>

I'm happy with my xml structure, but is there a more compact/efficient method of writing out the code for the jqeury? Every li in the nav has a unique id as well in case that helps...

A: 

Since you're just appending the text in the same order as it occurs in the xml document, you can do this:

var cs = $("li#case_studies"); //Cache the <li> reference
$(xml).find("CaseStudies").each(function() {
  cs.append('<ul><li>' + $(this).children().text() + "</li></ul>");
});​

This caches the reference to the li#case_studies so you're not traversing the DOM each time finding it. Also you're doing 1/4 as many traversals of the XML in the loop since you're just looking at the child collection once instead of 4 finds.

This only works as an optimization as long as the order of the elements in the XML matches the order you want, from your question it does, just be aware of that in case that may change.

You can see an example of the code above working here.

Nick Craver
Wow, that is insanely helpful! Works like a charm...
Llamabomber