I’ve gotten my menu to expand by one level, but cannot figure out how to get it to expand a second time. What am I doing wrong?
HTML:
<ul id="nav">
<li><a href="#">Root</a>
<ul>
<li><a href="#">Option 1</a>
<ul>
<li><a href="">Link3</a></li>
<li><a href="">Lin4</a></li>
<li><a href="">Link5</a></li>
<li><a href="">Link6</a></li>
</ul>
</li>
<li><a href="#">Option2</a>
<ul>
<li><a href="">Link3</a></li>
</ul>
</li>
</ul>
</li>
</ul>
CSS:
ul {
padding: 0px;
margin: 0px;
list-style: none;
background-color: #53BF58;
width: 10em;
}
li ul {
display: none;
background-color: #86EF8A;
}
li.active ul {
display: block;
}
li ul li ul {
display: none;
background-color: #86EF8A;
}
li ul li.active ul {
display:block;
}
Javascript:
function hideAll() {
var navList = document.getElementById("nav");
for (var i=0; i<navList.childNodes.length; i++) {
var node = navList.childNodes[i];
if (node.tagName == "LI") {
node.className = node.className.replace(new RegExp("\s?active", "i"), "");
}
}
}
window.onload = function () {
var navList = document.getElementById("nav");
for (var i=0; i<navList.childNodes.length; i++) {
var node = navList.childNodes[i];
if (node.tagName == "LI") {
node.onclick = function() {
hideAll();
this.className += " active";
}
}
}
}
childNodesonly contains the direct children of the element–you need to recurse thechildNodesof each node as well.I highly recommend that you use a framework like jQuery (http://jquery.com) to make the code simpler:
http://jsfiddle.net/jDEhU/5/