Removing "class name" from all siblings and adding it to the active element in jQuery

StackOverflow https://stackoverflow.com/questions/21843683

  •  13-10-2022
  •  | 
  •  

Question

I am working on a menu, within which only an active a element needs to have the active class (hyperactive). When I click on some other li element, I need to remove the active class from all other a siblings and add it on the clicked li.

This is the HTML:

            <ul class="main-links"> 

                <li id="ol" class="twist" data-id-name="oli" data-video-flv="europe-1.flv" data-video-m4v="europe-1.m4v">
                    <a href="#ol" class="hyperactive"><img src="imgs/btn1.jpg" width="237" height="104" style="margin-right:3px;" alt=""></a>
                </li>
                <li id="fl" class="twist" data-id-name="fl" data-video-flv="latam-2.flv" data-video-m4v="latam-2.m4v">
                    <a href="#fl"><img src="imgs/btn2.jpg" width="237" height="104" style="margin-right:3px;" alt=""></a>
                </li>
                <li id="jo" class="twist" data-id-name="jo" data-video-flv="na-1.flv" data-video-m4v="na-1.m4v">
                    <a href="#jo"><img src="imgs/btn3.jpg" width="237" height="104" style="margin-right:3px;" alt=""></a>
                </li>
                <li id="ra" class="twist" data-id-name="ra" data-video-flv="sa-1.flv" data-video-m4v="sa-1.m4v">
                    <a href="#ra"><img src="imgs/btn4.jpg" width="237" height="104" alt=""></a>
                </li>

            </ul>

This is what I tried through jQuery:

    var check_for_main_links = $(this).parent().attr('class');
    if (check_for_main_links.indexOf("twist") >= 0) {

        console.log ($(this).attr('class'));

        var $immediate_parent =  $(this).parent();
        $immediate_parent.siblings().each(function() {
            //$('span').remove();
            $('li').removeClass("active");
        }
        var $elem_name = $p.attr('data-id-name');
        var new_position = $("#"+$elem_name).position().top;
        //console.log("Element Name " + $elem_name + " position is " + new_position );

        top_position = new_position + 40;
    }
Was it helpful?

Solution

You can do like this:

$('ul.main-links li').click(funntion() {
    $('ul.main-links li a').removeClass('hyperactive');
    $(this).find('a').addClass('hyperactive');
});

OTHER TIPS

Try this:

$('ul.main-links li a').click(function() {
    $('ul.main-links li a').removeClass('hyperactive');
    $(this).addClass('hyperactive');
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top