Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 261
user3733831 Avatar asked Nov 19 '25 03:11

user3733831


2 Answers

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>
like image 83
Rory McCrossan Avatar answered Nov 20 '25 17:11

Rory McCrossan


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>
like image 41
Dipiks Avatar answered Nov 20 '25 16:11

Dipiks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!