Html – Bootstrap toggle button icon and text at the same time

csshtmljquerytwitter-bootstraptwitter-bootstrap-3

I am using Bootstrap 3 with Jquery. I have a button that contains an icon in a span tag.(using glypicon of bootstrap)

<button id="swapArchived" class="btn btn-default btn-sm showArchived">
       <span class="glyphicon glyphicon-road"></span> Show Archived
</button>

I want to change the icon and text when clicked. Is there any better way other than,

$('#swapArchived').on('click', function () {
    var $el = $(this);
    if($el.hasClass('showArchived'))
    {
      $el.html('<span class="glyphicon glyphicon-fire"></span> Show Incomplete');
    }
    else
    {      
      $el.html('<span class="glyphicon glyphicon-road"></span> Show Archived');
    }
      $el.toggleClass('showArchived');
  });

I was curious whether I can toggle button text and span class at the same time. Trying to avoid writing span on every click.

Thanks-

Best Answer

Try

jQuery(function ($) {

    $('#swapArchived').on('click', function () {
        var $el = $(this),
            textNode = this.lastChild;
        $el.find('span').toggleClass('glyphicon-fire glyphicon-road');
        textNode.nodeValue = 'Show ' + ($el.hasClass('showArchieved') ? 'Incomplete' : 'Archived')
        $el.toggleClass('showArchieved');
    });
});

Demo: Fiddle