yogesh84
yogesh84

Reputation: 181

Add a selected class to the clicked element and remove it from others

I have ul li structure like this

     <div id="categoryTree">
  <ul>
    <li id="cat_15"> <a class="hasSubCat"  href="javascript:void(0);"><img src="images/icons/folder.gif" border="0" alt="Folder" title=" Folder ">North India</a>
      <ul>
        <li id="cat_17"> <a class="hasSubCat"  href="javascript:void(0);"><img src="images/icons/folder.gif" border="0" alt="Folder" title=" Folder ">All India</a>
          <ul>
            <li id="cat_31"> <a class=""  href="javascript:void(0);"><img src="images/icons/folder.gif" border="0" alt="Folder" title=" Folder ">First Class</a> </li>
            <li id="cat_32"> <a class=""  href="javascript:void(0);"><img src="images/icons/folder.gif" border="0" alt="Folder" title=" Folder ">Luxury Level</a> </li>
            <li id="cat_33"> <a class=""  href="javascript:void(0);"><img src="images/icons/folder.gif" border="0" alt="Folder" title=" Folder ">Oulent Level</a> </li>
          </ul>
        </li>
      </ul>
    </li>
    <li id="cat_16"> <a class="hasSubCat"  href="javascript:void(0);"><img src="images/icons/folder.gif" border="0" alt="Folder" title=" Folder ">South India</a> </li>
    <li id="cat_37"> <a class=""  href="javascript:void(0);"><img src="images/icons/folder.gif" border="0" alt="Folder" title=" Folder ">All India</a> </li>
  </ul>
</div>

i wan to add a selected class to the clicked and remove it from others

i am using following code to do this

$('#categoryTree li').on('click',function(){
        $('#categoryTree li').removeClass('selected');
        $(this).addClass('selected');
        });

but every time class is added to the top li.please help ..... Thanks in Advance

Upvotes: 1

Views: 96

Answers (3)

Brijesh Bhatt
Brijesh Bhatt

Reputation: 3830

You can try this, using e.stopPropagation() which prevents the bubbling of event to parent li.

$('#categoryTree li').on('click',function(e){
    e.stopPropagation();
    $(this).closest("div").find("li.selected").removeClass("selected");
    $(this).addClass('selected');
});

Upvotes: 0

Rob
Rob

Reputation: 12872

I dont see an id of #categoryTree so we are missing some information here but it seems you want to remove the class from the selected siblings. You can do that like this...

$('#categoryTree li').on('click',function(){
    $(this).addClass('selected').siblings().removeClass('selected');
});

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388446

It is because of event propagation, where the click event in a child get propagated to the parent element. You can prevent it by calling Event.stopPropagation();

$('#categoryTree li').on('click', function (e) {
    e.stopPropagation();
    $('#categoryTree .selected').removeClass('selected');
    $(this).find('a').addClass('selected');
});

Upvotes: 0

Related Questions