Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if statement inside a variable

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

like image 990
BillZ Avatar asked Dec 02 '08 21:12

BillZ


2 Answers

You 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.

like image 112
Johannes Schaub - litb Avatar answered Sep 18 '22 21:09

Johannes Schaub - litb


var myVar += (myVar2 != false ? "Link 2" : "");

Ternary conditional operator etc.

like image 39
Thom Avatar answered Sep 21 '22 21:09

Thom