nutman
nutman

Reputation: 569

How do I expand this CSS list?

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";
            }
        }
    }
}

Upvotes: 0

Views: 788

Answers (2)

Andy Edinborough
Andy Edinborough

Reputation: 4427

childNodes only contains the direct children of the element--you need to recurse the childNodes of 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/

$('#nav').delegate('li', 'click', function() {
    var self = $(e.target), //get a reference to the clicked element
        active = self.parents().andSelf() //select all li's that should be active
            .addClass('active'); //and activate them
    $('#nav .active').not(active).removeClass('active'); //deactivate others  
});

Upvotes: 1

Brett
Brett

Reputation: 4061

I think the problem is that you're only looping through the first level of nodes in your list. You need to go through the child elements of each subsequent list and add an onClick function to keep it expanding.

Upvotes: 0

Related Questions