Barry Michael Doyle Barry Michael Doyle - 2 months ago 25
Javascript Question

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. Any help would be much appreciated.

Answer

Fairly straightforward - better to use a $.click() function and get your classes right:

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

What I did up here was add the class of toggle-icon to the top link, and the class of icon-toggle to the span of the glyphicon...the JS is as follows:

// On Toggle-Icon Click
$('.toggle-icon').click(function(){
// Set Icon To toggle in function
var IconToToggle = $(this).find('.icon-toggle');
// If the icon is the bottom icon
if (IconToToggle.hasClass('glyphicon-triangle-bottom')) {
// Change the icon to the top icon
IconToToggle.removeClass('glyphicon-triangle-bottom').addClass('glyphicon-triangle-top');
// Otherwise
} else {
// Change the top icon to the bottom icon
IconToToggle.removeClass('glyphicon-triangle-top').addClass('glyphicon-triangle-bottom');
}
})

Annotations added so you can read the code better. Hope this helps!

https://jsfiddle.net/khxehd05/

Comments