'How to change a class when one of the elements classname change?
I have this menu of elements, what is the best approach to change the last div element from hidden to visible when one of the elements with class closed changes to open using Jquery, What i want is when i click on one of the li and change it from closed to , i want to change the dynamic ul to display none or block, do i need to loop over all the elements and check their class?
<ul class="groupmenu">
<li class="closed"></li>
<ul class="level1"></ul>
<li class="closed"></li>
<ul class="level1"></ul>
<li class="closed"></li>
<ul class="level1"></ul>
<li class="closed"></li>
<ul class="level1"></ul>
<li class="closed"></li>
<ul class="level1"></ul>
<li class="closed"></li>
<ul class="level1"></ul>
<li class="closed"></li>
<ul class="level1"></ul>
<li class="closed"></li>
<ul class="level1"></ul>
<li class="closed"></li>
<ul class="level1"></ul>
<li class="closed"></li>
</ul>
<div class="dynamic hidden"></div>
Solution 1:[1]
First of all, your ul.level1 elements should be wrapped in li elements.
Then, on click of a li.closed element, you could :
- toggle the visibility of its
ul.level1child element. - toggle the visibility of your
div.dynamicelement using!$("ul.level1:not(.hidden)").length. It will return a boolean whose value will befalseif there is at least 1ul.level1element that does not have the.hiddenclass. Otherwise it will returntrue.
$("li.closed").click(function() {
$(this).find("ul.level1").toggleClass("hidden");
$("div.dynamic").toggleClass("hidden",!$("ul.level1:not(.hidden)").length);
});
.hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="groupmenu">
<li class="closed">
ul closed
<ul class="level1 hidden">
<li>visible</li>
</ul>
</li>
<li class="closed">
ul closed
<ul class="level1 hidden">
<li>visible</li>
</ul>
</li>
<li class="closed">
ul closed
<ul class="level1 hidden">
<li>visible</li>
</ul>
</li>
<li class="closed">
ul closed
<ul class="level1 hidden">
<li>visible</li>
</ul>
</li>
</ul>
<div class="dynamic hidden">
dynamic
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
