Grant G
Grant G

Reputation: 386

jQuery Accordion Add Class to Current Href and Its Parent Href

I have a problem adding a class to two elements when an href is clicked in an accordion menu. Remove instance of "current" class, add a class "current" to the sub-menu item clicked and also its parent item too. I have got the accordion working, as far as I click the parent menu item and the sub-menu appears. In this example, I mean I click "Second" and "Item 2.1" and "Item 2.1" appear. Click "Third" and "Second" and its children are hidden and Third and its children are shown. What I want to do is, once a child is clicked, add "current" to that child href element as well as its parent href (e.g. click href ID "two-one" and add "current" class to this element as well as to its "nav-subtitle" ID) and remove the "current" class from the current href.

This is the HTML:-

        <ul id="navigation">

            <li>
                <a href="index.html" class="nav-subtitle current">
                    Home
                </a>       
            </li>

            <li> 
                <a href="#" class="nav-subtitle">
                Second
                </a>
                <ul>
                    <li><a href="#" id="two-one">Item 2.1</a></li>
                    <li><a href="#" id="two-two">Item 2.2</a></li>
                </ul>
            </li>

            <li>
                <a href="#" class="nav-subtitle">
                    Third
                </a>
                <ul>
                    <li><a href="#" id="three-one">Item 3.1</a></li>
                    <li><a href="#" id="three-two">Item 3.2</a></li>
                    <li><a href="#" id="three-three">Item 3.3</a></li>                      
                </ul>
            </li>
        </ul>

I have tried the following jQuery but the 'parent' element ends up adding 'current' class to the li element, not the href with class nav-subtitle. If I specify "nav-subtitle" ID, the whole function fails:-

$("#two-one").click(function(){
        $( "#nav-subtitle" ).removeClass("current");
        $(this).parent().parent().parent("#nav-subtitle").addClass("current");   
        $(this).addClass("current");
});

Upvotes: 0

Views: 491

Answers (1)

Grant G
Grant G

Reputation: 386

I believe this code does what I need it to do.

$("#two-one").click(function(){
        $('a.current').removeClass('current');
        $(this).parent().parent().siblings().addClass('current');
        $(this).addClass('current');
});

Remove 'current' class from element with class 'current', add 'current' to the parent href and finally add class 'current' to the href clicked on.

Upvotes: 0

Related Questions