Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery changing text and toggleClass at same time

Tags:

html

jquery

css

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>
like image 369
gunslinger85 Avatar asked Sep 12 '26 22:09

gunslinger85


1 Answers

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);
  });
like image 98
plsankar Avatar answered Sep 15 '26 12:09

plsankar



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!