javascriptjqueryhtmlcsstwitter-bootstrap

jQuery/JS onclick change class of element inside link clicked


I have a couple of drop downs using bootstrap and I want to code in a simple function to change the class of my span element inside the link that is clicked.

To clarify, here's an example of the HTML I have:

<a data-toggle="collapse" href="#collapse-panel" aria-expanded="false"
    onclick="toggleIcon()">
    <span class="glyphicon glyphicon-knight"></span>
    Drop Down Title
    <span class="glyphicon glyphicon-triangle-bottom"></span>
</a>
<div class="collapse" id="collapse-panel">
   <!-- content -->
</div>

I am looking for a function (using JS or jQuery) which can toggle the second span class to change between glyphicon glyphicon-triangle-bottom and glyphicon glyphicon-triangle-top.

Bear in mind, this function has to work for multiple drop-downs.


Solution

  • $('a[data-toggle="collapse"]').click(function() {
      $(this)
        .find('.glyphicon-triangle-bottom, .glyphicon-triangle-top')
        .toggleClass('glyphicon-triangle-top glyphicon-triangle-bottom');
    });
    

    Also remove onclick="toggleIcon()"

    This should work for all anchor tags that have data-toggle="collapse" attribute.