0

I have some drop-down menus from a plugin that do not display their contents in alphabetical or an ascending/descending order.

The lists look like this in the inspector:

<ul class="options">
    <li class = "opt">
        <span><i></i></span>
        <label> BAC </label>
    </li>
    <li class = "opt">
        <span><i></i></span>
        <label> ACD </label>
    </li>
    <li class = "opt">
        <span><i></i></span>
        <label> FBC </label>
    </li>
</ul>

I would like to sort these li's by the contents of the label.

The order of the list is currently whatever was entered into a spreadsheet last is at the top.

I have attempted some solutions found here including this one Sort an html list with javascript

However, the order of my drop down remains the same.

This is my first time asking a question, let me know if I left out anything crucial. Thanks.

  • Have you checked wether the plugin gave functionality for sorting or not? – Jogi Mehul Dec 22 '18 at 03:49
  • After trying the answer below without success I kept looking and the plugin is using another plugin called sumoselect that does not allow you to sort alphabetically. I am still hoping to find a workaround but I am still trying to figure out how sumo select works. Thanks for the help. – jrowle34 Dec 26 '18 at 00:27

1 Answers1

0

You can sort a jQuery collection and append that collection to parent

$('ul.options').append(function() {
  return $(this).children().sort(function(a, b) {
    var aText = $(a).find('label').text().trim(),
        bText = $(b).find('label').text().trim();
    return aText.localeCompare(bText);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="options">
  <li class="opt">
    <span><i></i></span>
    <label> BAC </label>
  </li>
  <li class="opt">
    <span><i></i></span>
    <label> ACD </label>
  </li>
  <li class="opt">
    <span><i></i></span>
    <label> FBC </label>
  </li>
</ul>
charlietfl
  • 170,828
  • 13
  • 121
  • 150