javascriptjqueryremoveclass

removeclass doesnt work


i have a very simple question, actually this is not the question, this is fixing the javascript mistake, anyway, here is the code:

    $(document).ready(function() {
        $('#accordion a.item').click(function () {
            $(this).addClass('selected');
            $(this).removeClass('selected');
            $('#accordion li').children('ul').slideUp('slow'); 
            $(this).siblings('ul').slideDown('slow');  
        });
    });

and the html:

<ul id="accordion">
    <li>
        <a href="#" class="item">BANKS</a>
        <ul>BLA BLA BLA</ul>
    </li>
    <li>
        <a href="#" class="item">PETROL</a>
        <ul>BLA BLA BLA</ul>
    </li>
</ul>

when i click one of the link, the 'selected' class is added to it, but when i click the other link, the class 'selected' is not removing, what can be the mistake there?

thank you all for helping! i really appreciate it!


Solution

  • It's not clear what you are trying to do, but it looks like you want to add the class to the clicked element and remove it from the all its siblings. Your current code adds and removes the class to the same element, which ends up not doing anything.

    You probably want something like

    $(document).ready(function() {
        $items = $('#accordion a.item'); // all the items
        $items.click(function () {
            $items.removeClass('selected'); // remove class from everything
            $(this).addClass('selected'); // add class to clicked item
            $('#accordion li').children('ul').slideUp('slow'); 
            $(this).siblings('ul').slideDown('slow');  
        });
    });