I have a menu I want to sort alphabetically. I found this:
Sort DIVs alphabetically without destroying and recreating them?
I applied the jQuery script to "sort". Works great. The only logical problem is that the hidden divs (class: hidden) don’t follow, they show/hides by click on "btn_expand" and toggle next div.
I have tried some different ways to develop the script but I don’t find any good solution to it. Ends up with a bunch of code and messy results. It should be solved as if next div hasClass "hidden" then "bring it with" and append after the "btn_expand" but I fail with that. Can somebody with more skills maybe help out, it would make my day. 🙂
Thanks!
$('.sort').sort(function(a, b) {
if (a.textContent < b.textContent) {
return -1;
} else {
return 1;
}
}).appendTo('body');
$(".btn_expand").on('click', function() {
$(this).next("div").toggle();
});
.btn_expand {
background: red;
}
.hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Without sorting</p>
<div class="btn_expand">CCC</div>
<div class="hidden">Hidden content shown by press CCC</div>
<div class="btn_no_expand">EEE</div>
<div class="btn_no_expand">AAA</div>
<div class="btn_no_expand">DDD</div>
<div class="btn_expand">BBB</div>
<div class="hidden">Hidden content shown by press BBB</div>
<br><br>
<p>With sorting</p>
<div class="btn_expand sort">CCC</div>
<div class="hidden">Hidden content shown by press CCC</div>
<div class="btn_no_expand sort">EEE</div>
<div class="btn_no_expand sort">AAA</div>
<div class="btn_no_expand sort">DDD</div>
<div class="btn_expand sort">BBB</div>
<div class="hidden">Hidden content shown by press BBB</div>
2
Answers
You could sort, then for each matched element, check if next sibling has class
.hidden
, if so, add it to the selector, and then append to body:Or, in an even shorter form, you can do this: