简体   繁体   中英

How to add class to all li but not to clicked li using jquery

I want to add a hidden class to all li but not to the li which was clicked. How can I do this using jQuery?

<ul class="render-menu">        
  <li class="font-size">list 1</li>
  <li class="font-size">list 2</li>
  <li class="font-size">list 3</li>
  <li class="font-size">list 4</li>
</ul>
jQuery(".render_menu li").on('click', function() { 
  alert();
  jQuery(".render_menu").not($(this)).parent().addClass('hidden');
});

Firstly note that your class in the HTML is render-menu , yet the JS was using render_menu . You need to make them consistent.

With regard to the issue, you're adding the class to the parent() of the li , ie. the ul , so all the child elements are being affected by the class. To fix this, use siblings() to get all the li elements you require before calling addClass() . Try this:

 $(".render-menu li").on('click', function() { $(this).siblings().addClass('hidden'); }); 
 .hidden { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul class="render-menu"> <li class="font-size">list 1</li> <li class="font-size">list 2</li> <li class="font-size">list 3</li> <li class="font-size">list 4</li> </ul> 

Change your JS code to below

jQuery(".render_menu li").on('click', function () {
            alert();

            jQuery(".render_menu li").not($(this)).addClass('hidden');

        });

You are comparing ul instead of li to add class

You can try the following

 $('.render-menu li').on('click',function(){ $('.render-menu li').removeClass('hidden').not(this).addClass('hidden'); }); 
 .hidden{ color:lightgray; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="render-menu"> <li class="font-size">list 1</li> <li class="font-size">list 2</li> <li class="font-size">list 3</li> <li class="font-size">list 4</li> </ul> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM