skyguy skyguy - 2 months ago 28x
Javascript Question

JS: change icon in div on Bootstrap collapse?

Ok, I have tried several methods (JS and CSS) and I cannot get this to work. I need to change a plus font awesome icon to a minus (i.e either add a new div in place of the other or just change the class of the div) when a div is collapsed via Bootstrap.

I have looked at similar questions but can't solve this for the life of me.

Here is my html:

<div class="panel-heading" role="tab" id="headingOne">

<h4 class="panel-title">

<a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="false" aria-controls="collapseOne"><i class="fa fa-plus-square-o"></i><i class="fa fa-minus-square-o"></i><span style="margin-left: 12px; display: inline-block;"></span>Lab Focus: Cloud Management with vRealize Operations & <nobr>vRealize Automation</nobr></a>



<div id="collapseOne" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne">

<div class="panel-body">

<span style="font-family:'proximanova-light', sans-serif;font-size:15px; line-height:19px; text-align:left; color: #565656;">

<p>Deliver intelligent operations management across physical, virtual, and cloud infrastructures and accelerate the deployment and management of applications and compute services, improving business agility and operational efficiency.</p>

When I click the div and it opens (it is an accordion div) I need to change the
then back again when the div collapses. Because I have 8 of these, I have tried using JS and

$(".collapsed").click(function() {
console.log("panel clicked");
var downPanel = "";
$('.fa-plus-square-o', this).remove();
$('.fa-plus-minus-o', this).add();

And several other variations but nothing worked. I then tried CSS changing the class to collapsed1:

.collapsed1 .fa-minus-square-o,
.collapsed1.collapsed .fa-minus-square-o {
display: inline-block;
.collapsed1.collapsed .fa-plus-square-o,
.collapsed1 .fa-plus-square-o {
display: none;

However this results in either just the minus or both icons showing all the time. I am new to JS and need some help.

How can I change the icon depending on if the div is collapsed or not?


Just toggle the classes:

$('.collapsed').on('click', function() {