I have the following html li which contains list of usernames which are defined as
available or not available , how can I sort the list so that if the <button>
inside <li>
has the text “Available” moves to the top of the list and “Not Available” moves to the bottom of the list?
<ul class="list-group" id="prefixed-list">
<li class="list-group-item active" aria-current="true">Prefixed List</li>
<li class="list-group-item">mydavid
<button type="button" class="btn btn-danger float-end" aria-expanded="false">Not Available</button>
<br>
<br>
<div class="collapse">
Other text
</div>
</li>
<li class="list-group-item">jamesdave3
<button type="button" class="btn btn-danger float-end" aria-expanded="false">Not Available</button>
<br>
<br>
<div class="collapse">
Other text
</div>
</li>
<li class="list-group-item">imdavid39494
<button type="button" class="btn btn-success float-end" aria-expanded="false">Available</button>
<br>
<br>
<div class="collapse">
Other text
</div>
</li>
</ul>
2
Answers
The following snippet illustrates how you can sort the
<li>
elements in a given<ul>
with a custom sort function. In this example, the contents of the list items are compared as numbers, but you can adapt the function to suit your needs:The sorted items are then added in the right sequence as children of
<ul>
. There is no need to remove them first, because adding an element automatically removes it from its former position in the document tree.You can use
.filter()
to select thoseli
elements that have a button with a text that has "Not", and re-append them to theul
container element. That way they actually move to the bottom of the list: