Anthony Anthony - 5 months ago 25
jQuery Question

Jquery click and add Active in different ul but same class name

I have lot of menu UL elements and same class name,

how can i do for the ul children's li click and add class "active" to which clicked,and click other li inside the same ul will remove active and add the active class to clicked li,i tried google for a while,but no find out the solution,thanks

jQuery(".uls").each(function(index){

jQuery(this).children('.btn.btn-primary').on("click", function(){
jQuery('.btn.btn-primary').removeClass('active');
jQuery(this).addClass('active');
});


});


HTML:

<ul class="uls">
<li class="btn btn-primary"></li>
<li class="btn btn-primary"></li>
<li class="btn btn-primary"></li>
<li class="btn btn-primary"></li>
</ul>

<ul class="uls">
<li class="btn btn-primary"></li>
<li class="btn btn-primary"></li>
<li class="btn btn-primary"></li>
<li class="btn btn-primary"></li>
</ul>

Answer

You could do something like this with the help of $.fn.siblings method:

$('.uls').on('click', '.btn', function() {
  $(this).siblings().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 class="uls">
  <li class="btn btn-primary">one</li>
  <li class="btn btn-primary">two</li>
  <li class="btn btn-primary">three</li>
  <li class="btn btn-primary">four</li>
</ul>

<ul class="uls">
  <li class="btn btn-primary">one</li>
  <li class="btn btn-primary">two</li>
  <li class="btn btn-primary">three</li>
  <li class="btn btn-primary">four</li>
</ul>