Daniel Daniel - 4 months ago 27
Javascript Question

how to add or remove class from html elements with jQuery

I was trying to add class on a current

<a></a>
and wanted to remove that active class from other
<a></a>
. i was trying

MY FIDDLE

HTML

<ul>
<li>
<a href="#" class="active">
Home
</a>
</li>
<li>
<a href="#">
About
</a>
</li>
<li>
<a href="#">
Service
</a>
</li>
</ul>


jQuery

$('ul li a').click(function(e){
e.preventDefault();
$(this).addClass('active').siblings().removeClass('active');
});

Answer

$('ul li a').click(function(e){
 e.preventDefault();
  $('ul li a').removeClass('active')
 $(this).addClass('active');
});
.active{color:red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>
   <a href="#" class="active">
    Home
   </a>
  </li>
  <li>
   <a href="#">
    About
   </a>
  </li>
  <li>
   <a href="#">
    Service
   </a>
  </li>
</ul>
jQuery

You can remove all the active class from anchor then add the active class to clicked anchor

Comments