Bootstrap toggle button icon and text at the same time

13,756

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

Share:
13,756
Jhankar Mahbub
Author by

Jhankar Mahbub

Web developer, interested in client side development and always a curious learner.

Updated on June 13, 2022

Comments

  • Jhankar Mahbub
    Jhankar Mahbub almost 2 years

    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-