JQuery changing text and toggleClass at same time

Viewed 189

On a click event, I would like to change text and toggle 2 different classes at the same time. I have set my code up below but it only performs one and not the other

$(document).ready(function() {

  $('.more-benefits-btn').click(function() {


    $(this).text($(this).text() == 'Show Less' ? 'Show More Benefits' : 'Show Less');
    $("i", this).toggleClass('fal fa-chevron-down fal fa-chevron-up');
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<span class="more-benefits-btn">Show More Benefits&nbsp;<i class="fal fa-chevron-down"></i></span>

2 Answers

Probably because it changes the whole content of the button

$(document).ready(function () {

$('.more-benefits-btn').click(function () {
  var $this = $(this).find('span'); 
    $this.text($this.text() == 'Show Less' ? 'Show More Benefits' : 'Show Less');
    $(this).find('i').toggleClass('rotate');
});
});
i{
display: inline-block;
transition:all ease .5s;
}
i.rotate{
transform:rotate(180deg);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="more-benefits-btn"> <span> Show More Benefits </span><i>V</i></button>

The reason the class of <i> is not toggling because when you use text method the <i> element is removed.

Use this code

  $('.more-benefits-btn').click(function() {
  var i = $("i", this);
  $(this).text($(this).text() == 'Show Less' ? 'Show More Benefits' : 'Show Less');
  i.toggleClass('fa-chevron-down fa-chevron-up');
  $(this).append(i);
  });
Related