Barry Michael Doyle Barry Michael Doyle - 1 year ago 159
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

I have:

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

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

Bear in mind, this function has to work for multiple drop-downs. Any help would be much appreciated.

Answer Source

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>
<div class="collapse" id="collapse-panel">
<!-- content -->

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
// 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
// Otherwise
} else {
// Change the top icon to the bottom icon

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download