Alex Zahir Alex Zahir - 7 months ago 10
HTML Question

jQuery if div has a class of 'in' change another div's background color

I want to make the background of a div class

.panel-heading
to blue if the
.panel-collapse
inside the div
.panel
has a class of
in
. I am using Bootstrap accordion.

This is my HTML:

<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
Lipsum set dolor
<span class="pull-right glyphicon glyphicon-minus"></span>
</a>
</h4>
</div>
<div id="collapseOne" class="panel-collapse collapse in">
<div class="panel-body">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since
</div>
</div>
</div><!-- end panel -->


I tried something simple like this but it is not working:

if ($('.panel-collapse').hasClass('in')) {
$(this).closest('.panel-heading').css("background", "blue");
}
else {
$(this).closest('.panel-heading').css("background", "red");
}

Answer

.panel-heading is sibling of .panel-collapse. Try like following using siblings() method.

$('.in').siblings('.panel-heading').css("background", "blue");

$('.collapse').on('shown.bs.collapse', function () {
    var panelHeading = $(this).siblings('.panel-heading');
    panelHeading.find(".glyphicon-plus").toggleClass("glyphicon-minus glyphicon-plus");
    panelHeading.css("background", "blue");
}).on('hidden.bs.collapse', function () {
    var panelHeading = $(this).siblings('.panel-heading');
    panelHeading.find(".glyphicon-minus").toggleClass("glyphicon-minus glyphicon-plus");
    panelHeading.css("background", "red");
});

UPDATED FIDDLE