I am building a conditional navigation menu that has 3 levels (the 3rd level added today by business, no worries its not like I launch next week. Oh wait I do:)). I have a javascript var that contains the html for my first conditional level. I am now trying to insert another level inside of the first.
var myVar = '<ul class="linksUnit">';
var myVar += '<li>Link 1</li>';
var myVar += if (myVar2 != false) {document.write("Link 2")};
var myVar += '</ul>';
Any help would be greatly appreciated.
Thanks
I am building a conditional navigation menu that has 3 levels (the 3rd level added today by business, no worries its not like I launch next week. Oh wait I do:)). I have a javascript var that contains the html for my first conditional level. I am now trying to insert another level inside of the first.
var myVar = '<ul class="linksUnit">';
var myVar += '<li>Link 1</li>';
var myVar += if (myVar2 != false) {document.write("Link 2")};
var myVar += '</ul>';
Any help would be greatly appreciated.
Thanks
Share Improve this question asked Dec 2, 2008 at 21:31 BillZBillZ 2473 gold badges4 silver badges9 bronze badges2 Answers
Reset to default 10You should write that this way (knowing little javascript myself, but i think this is right):
var myVar = '<ul class="linksUnit">';
myVar += '<li>Link 1';
if (myVar2) { // note != false means true
// insert a nested unordered list
myVar += '<ul>';
myVar += '<li>Link 2</li>';
myVar += '</ul>';
}
myVar += '</li>';
myVar += '</ul>';
var
is only needed the first time you declare the variable.
W3C DOM
If you build up the string that you append / insert into your document like that, it will soon become quite confusing. For example, if you want to change something, you have to fiddle with the strings. Better you use the W3C DOM
API, which is standardized and provides a clean way to build up a element tree which can be appended to any child element into the document tree. Here you will find a nice introduction into the matter: W3C DOM Introduction. After you read this, you can start looking at the methods of W3C DOM. Here is a good reference: DOM2 Reference. Start with document.createElement
and work your way through.
var myVar += (myVar2 != false ? "Link 2" : "");
Ternary conditional operator etc.