简体   繁体   中英

Remove class if exist and add new one using jquery

I have a markup for <ul> as below:

<ul>       
  <li class=""><a href="">Insulated And Extruded</a></li>
  <li class=""><a href="">Grille Type Rolling</a></li>
  <li class="active2"><a href="">PVC High Speed Doors</a></li>
  <li class=""><a href="">Swinging doors</a></li>
</ul> 

Here I want to check li has a class named active2 , and if it does then I need to remove that class and need to add different class to that li .

This is how I tried it in jQuery:

if($('ul li').hasClass('active2')) {
  $(this).removeClass('active2').addClass('active1'); 
}

But it doesn't work.

Can anybody help me to figure this out?

To use hasClass() you'd need to loop through all the li elements and check them individually.

However there's no need for hasClass() here at all as you can select the .active2 elements directly and call toggleClass() on them, like this:

 $('ul li.active2').toggleClass('active2 active1'); 
 .active1 { background-color: yellow; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li class=""><a href="">Insulated And Extruded</a></li> <li class=""><a href="">Grille Type Rolling</a></li> <li class="active2"><a href="">PVC High Speed Doors</a></li> <li class=""><a href="">Swinging doors</a></li> </ul> 

You do not need hasClass() , You can simply do this :

 $('ul li.active2').removeClass('active2').addClass('active1'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li class=""><a href="">Insulated And Extruded</a></li> <li class=""><a href="">Grille Type Rolling</a></li> <li class="active2"><a href="">PVC High Speed Doors</a></li> <li class=""><a href="">Swinging doors</a></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