MrKainig MrKainig - 1 month ago 9
CSS Question

Jquery Accordion function, alter class of parent

I have a bootstrap accordion table which is working fine. The glyphicon indicates which tablerows children-row is currently expanded. But something with the function seems to be wrong it doesn't change the class of the ancestor element as expected.

$('.accordion-text').on('shown.bs.collapse', function () {
$(this).closest(".indicator").removeClass("glyphicon-chevron-up").addClass("glyphicon-chevron-down");
});

$('.accordion-text').on('hidden.bs.collapse', function () {
$(this).closest(".indicator").removeClass("glyphicon-chevron-down").addClass("glyphicon-chevron-up");
});


Full code: http://jsfiddle.net/7pwg1j5f/616/

<tbody>
<tr id="package1" class="accordion-toggle" data-toggle="collapse" data-parent="#OrderPackages" data-target=".packageDetails1">
<td>123456</td>
<td>3</td>
<td><i class="indicator glyphicon glyphicon-chevron-up pull-right"></i>

</td>
</tr>
<tr>
<td colspan="3" class="hiddenRow">
<div class="accordion-text accordion-body collapse packageDetails1" id="">
<table>
<tr>
<td>Revealed item 1</td>
</tr>
<tr>
<td>Revealed item 2</td>
</tr>
</table>
</div>
</td>
</tr>



Answer

The way you were finding your .indicator element was not proper. It resides in the previous tr of .accordion elements parent tr. Just follow the structure and you will get the proper element. Also, you can combine both the events and use toggleClass instead of addClass and removeClass. So below is the updated solution.

$('.accordion1').on('shown.bs.collapse hidden.bs.collapse', function () {
    $(this).closest('tr').prev(".accordion-toggle").find('.indicator').toggleClass("glyphicon-chevron-up glyphicon-chevron-down");
});

.closest('tr') - fetches the parent of .accordion1 div.

.prev('.accordion-toggle') - fetches the previous sibling of the earlier obtained parent.

.find('.indicator') - find the .indicator element.

.toggleClass - toggles [add/removes] respective class.

Here is the Updated DEMO

Also note that I've made some changes in html to match the class