Alejandro Alejandro - 5 months ago 18
HTML Question

Trying to toggle html content with jQuery

Hey so I have this HTML and i want to change the icon when its clicked

<span class="esconderInput" id="esconderInput"><a href="#"><i class="fa fa-minus-square"></i></a></span>


and im trying to change it with jQuery with this code

$('#esconderInput').on('click',function(){
if ( $( '#esconderInput' ).html() == '<a href="#"><i class="fa fa-minus-square"></i></a>' ) {
$( this ).html( '<span class="esconderInput" id="esconderInput"><a href="#"><i class="fa fa-plus-square"></i></a></span>' );
console.log( $( this ).html() );
} else {
$( this ).html( '<span class="esconderInput" id="esconderInput"><a href="#"><i class="fa fa-minus-square"></i></a></span>' );
console.log( $( this ).html() );
}
} );


it works on the first time i click, but not on the following, any idea?

Thanks

Answer Source

Please try code given below:

$('#esconderInput').on('click',function()
{
     if ($( '#esconderInput' ).html() == '<a href="#"><i class="fa fa-minus-square"></i></a>' ) 
     {
          $( this ).html( '<a href="#"><i class="fa fa-plus-square"></i></a>' );
          console.log( $( this ).html() );
     }
     else 
     {
          $( this ).html( '<a href="#"><i class="fa fa-minus-square"></i></a>' );
          console.log( $( this ).html() );
     }
} );