Manoj A
Manoj A

Reputation: 335

How to change Inner html content with toogle class in Jquery?

This is my html code as shown in bellow,

<button  type="button" class="csk-landing-button-1">
    <i class="fa fa-plus-circle" aria-hidden="true"></i>
    <span>Device Requirement</span>
</button>

<script>
$('.csk-landing-button-1').click(function(){    
    $(this).find('i').toggleClass('fa-plus-circle fa-minus-circle')
});
</script>

Here i toogle .fa icon. But I want to chage <span> tag text also. So what can i do for that.

Upvotes: 0

Views: 57

Answers (3)

Matias Kinnunen
Matias Kinnunen

Reputation: 8540

You can use jQuery's .end() method to "end" the previous filter operation, in this case the .find('i') operation. Then you can chain another .find() to target the span.

$('.csk-landing-button-1').on('click', function() {
  const newText = 'New text';

  $(this)
    .find('i')
      .toggleClass('fa-plus-circle fa-minus-circle')
    .end()
    .find('span')
      .text(newText);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button  type="button" class="csk-landing-button-1">
    <i class="fa fa-plus-circle" aria-hidden="true"></i>
    <span>Device Requirement</span>
</button>

Of course you can also do this instead of chaining methods and using the .end() method:

$('.csk-landing-button-1').on('click', function() {
  const $this = $(this);
  const newText = 'New text';
  
  $this.find('i').toggleClass('fa-plus-circle fa-minus-circle');
  $this.find('span').text(newText);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button  type="button" class="csk-landing-button-1">
    <i class="fa fa-plus-circle" aria-hidden="true"></i>
    <span>Device Requirement</span>
</button>

Upvotes: 0

Poonam
Poonam

Reputation: 549

Here is your solution, Use .hasClass()

    $('.csk-landing-button-1').click(function () {
       $(this).find('i').toggleClass('fa-plus-circle fa-minus-circle');
       if($(this).find('i').hasClass('fa-plus-circle'))
          $(this).find('span').html("On plus");
       else 
          $(this).find('span').html("On minus");
    });

Upvotes: 1

Satpal
Satpal

Reputation: 133403

You can use .is(selector) or .hasClass(className) to check element has that class and perform the desired operation.

$('.csk-landing-button-1').click(function() {
  var i = $(this).find('i').toggleClass('fa-plus-circle fa-minus-circle');
  if (i.is('.fa-plus-circle')) { //i.hasClass('fa-plus-circle')
    $(this).find('span').text('Plus');
  } else {
    $(this).find('span').text('Minus');
  }
}).click();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="csk-landing-button-1">
    <i class="fa fa-plus-circle" aria-hidden="true"></i>
    <span>Device Requirement</span>
</button>

Upvotes: 2

Related Questions