Search code examples
javascriptjqueryalphabetical

How to sort contents of div alphabetically?


I have a dropdown menu with a long list of items and I want it to appear in alphabetical order.

<div id="myDropdown" class="dropdown-content">
          <a href="#john" id="john-link" class="anchor">
          <img src="images/logos/chelsea.png">John</a>
          <a href="#paul" id="paul-link" class="anchor">
          <img src="images/logos/tfc.png">Paul</a>
          <a href="#umar" id="umar-link" class="anchor">
          <img src="images/logos/realmadrid.png">Umar</a>
          <a href="#mass" id="mass-link" class="anchor">
          <img src="images/logos/inter.png">Mass</a>
          <a href="#carlos" id="carlos-link" class="anchor">
          <img src="images/logos/leverkusen.png">Carlos</a>
          <a href="#colla" id="colla-link" class="anchor">
        </div>

Is there a way with jQuery or javascript to sort my content alphabetically?


Solution

  • To avoid just moving the inner html, you can use the approach below.

    function sortMe(parent, children) {
        children.sort((a, b) => {
            if (a.innerText < b.innerText) {
                return -1
            }
            if (a.innerText > b.innerText) {
                return 1;
            }
            return 0;
        });
        children.detach().appendTo(parent);
    }
    

    Specify the parent and children (the elements used for sorting - in this case it is the innerText of the a tags):

    let parent = $("#myDropdown");
    let children = $("#myDropdown").children("a");
    

    Then call the function with the proper args:

    sortMe(parent,children);
    

    You shouldn't need to change the HTML for this approach to work.