Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manipulate all elements except the one currently clicked

Tags:

html

jquery

I wanted to know if there's a way to alter child elements while isolating the one that is currently clicked, so far I have a simple traversal with a click event handler inside as follows:

$(function() {
    $(".hd").children("ul").children().each(function(){
        $(this).click(function(){

            alert('Handler for .click() called');//Test (remove after completion)
        });
    })
});

<!--HTML to manipulate>
    <div class="hd">
                            <h2>Important  Information</h2>
                            <ul>
                                <li><a href="#">Faculty</a></li>
                                <li><a href="#">Staff</a></li>
                                <li><a href="#">Students</a></li>
                            </ul>
                        </div>

What I have are links in a <ul> that I'm treating as tabs. What I'm trying to do is add a class to the currently selected <li> while at the same time removing classes from all other <li> in the list. I'm thinking I might have it reversed, i.e. the click handler should go first and the traversal should go inside. My goal is as follows:

like image 973
kingrichard2005 Avatar asked Feb 27 '23 13:02

kingrichard2005


2 Answers

$('.hd > ul > li').click(function(){
   $(this).addClass('myClass').siblings().removeClass('someClass');
});

Note the difference in selector between Nick and I's solutions - mine is only going to grab direct children at each level while his will grab all ul li descendents.

like image 130
prodigitalson Avatar answered Mar 07 '23 20:03

prodigitalson


Try this:

$(function() {
  $(".hd ul li").click(function(){
    $(this).addClass("current").siblings().removeClass("current");
  })
});
like image 24
Nick Craver Avatar answered Mar 07 '23 20:03

Nick Craver