0

I am trying to list all categories in my XML file and link them with a javascript function which opens an xsl file.

I'keep getting this error: Novel is Undefined. where Novel is a category from the XML

Here is my code.

var root=myxmldoc.getElementsByTagName("CATEGORY");
        for (i=0;i<root.length;++i) {
            var catName=(root[i].childNodes[0].nodeValue);
            txt='<a href="#" onClick="javascript:Navigate('+catName+')">'+catName+'</a>';
            document.getElementById("left-sidebar").innerHTML+=txt; 

        }

In the code above, Navigate(var) is a function that loads various .XSL files for each category.

Please can anyone help me understand why the error keeps coming up?

Thanks

5
  • 1
    Does the error happen when the code above is executed, or when the link is clicked? Commented May 9, 2011 at 16:00
  • 1
    off topic, but you'd get better performance if you built txt as a string and did the innerHTML update just once, outside the loop. Commented May 9, 2011 at 16:00
  • 1
    can you provide the XML in this example? Commented May 9, 2011 at 16:01
  • @David Grayson - the error happened when the link is clicked @Spudley - i will try that, thank you for the tip :) @pixelbobby - I've been helped with the problem. But if you still want to see it, i will be glad to post it. Thank you Commented May 9, 2011 at 16:47
  • @Spudley, i can't seem to do what you suggested. could you help me out please? Commented May 9, 2011 at 18:57

1 Answer 1

2

When you generate the link, it'll come up as:

 <a href="#" onClick="javascript:Navigate(Novel)">Novel</a>

Note the lack of quotes around Novel, meaning Javascript will see that as a variable, which happens to not be defined.

You neeed to embed quotes in your string generation like this:

 txt='<a href="#" onClick="javascript:Navigate(\''+catName+'\')">'+catName+'</a>';
                                               ^^ here      ^^ and here

so that the HTML will look like:

 <a href="#" onClick="javascript:Navigate('Novel')">Novel</a>
Sign up to request clarification or add additional context in comments.

2 Comments

Oh okay i get it, thank you very much and it works. is there a reason why its written like [\''+catName+'\'] and not like ['\'+catName+'\']?
Because you need the escaped quote WITHIN your string. If it's outside, then it's just some random used-to-be-a-quote-but-isn't-anymore dangling around and breaking the syntax.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.