AlonsoCT AlonsoCT - 1 month ago 8
jQuery Question

Need to switch/remove class with siblings selector

I have two buttons, when I click any of one the function add the class "selected" but if I push the other button the two buttons keep the same class, I used the siblings selector but don't works correctly, ┬┐can you help me please?



$('.btn-switch-view').on('click', function() {
$(this).addClass('btn-switch-view-selected');
$('.btn-group').siblings('a.btn-switch-view-selected').removeClass('btn-switch-view-selected');
});

.btn-group .btn-default.btn-switch-view {
color: #b2b2b2;
}
.btn-group a.btn-default.btn-switch-view:hover,
a.btn-default.btn-switch-view-selected {
color: #1b4298!important;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div class="btn-group">
<a href="#" id="grid" class="btn btn-default btn-sm btn-switch-view">
<i class="fa fa-th-large" aria-hidden="true"></i>
</a>
<a href="#" id="list" class="btn btn-default btn-sm btn-switch-view">
<i class="fa fa-th-list" aria-hidden="true"></i>
</a>
</div>




Answer

You already have the anchor in this, now target the sibling anchors, and remove the class

$('.btn-switch-view').on('click', function() {
  $(this).addClass('btn-switch-view-selected')
         .siblings()
         .removeClass('btn-switch-view-selected');
});
.btn-group .btn-default.btn-switch-view {
  color: #b2b2b2;
}
.btn-group a.btn-default.btn-switch-view:hover,
a.btn-default.btn-switch-view-selected {
  color: #1b4298!important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="btn-group">
  <a href="#" id="grid" class="btn btn-default btn-sm btn-switch-view">
    <i class="fa fa-th-large" aria-hidden="true">Button</i>
  </a>
  <a href="#" id="list" class="btn btn-default btn-sm btn-switch-view">
    <i class="fa fa-th-list" aria-hidden="true">Button</i>
  </a>
</div>