Home > Mobile >  How to alphabetize the li's within each the respective section using jQuery
How to alphabetize the li's within each the respective section using jQuery

Time:02-01

I have an html list similar to the following: list items within the groups. I have destroyed several jQuery scripts at this point. I can't get into the sections and just alphabetize the li's. I have tried using :nth-child to get to the li's, but it doesn't work. Could anyone provide some insight please?

Thank you in advance.

  <h3 id="teams-01">TEAMS</h3></div>
<div>
<h3 align="left">vangard</h3>
</div>
<ul>
<li >Rates</li>
<li >Portfolio</li>
<li >Cases</li>
</ul>
<h3 align="left">Fedility</h3>
<ul >Rates
<li >Cases</li>
</ul>
<h3 align="left">McCoughlah</h3>
<ul>
<li >Rates</li>
<li >Portfolio</li>
<li >Cases</li>
</ul>
<h3 align="left">BrownRock</h3>
<ul>
<li >Portfolio</li>
<li >Cases</li>
</ul>

I have tried various os this, adjust the :nth to try pick only the li's:

$(function() { var $mylist = $("#list"); $mylist.children().detach().sort(function(a, b) { return $(a).text().localeCompare($(b).text()); }).appendTo($list); });

var mylist = $('#list'); 
var listitems = mylist.children('li').get(); listitems.sort(function(a, b) { return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase()); }) mylist.empty().append(listitems);

CodePudding user response:

Kindly use this code

$(document).ready(function() {
  $('#some-id ul').each(function() {
    $(this).children().detach().sort(function(a, b) {
      return $(a).text().localeCompare($(b).text());
    }).appendTo($(this));
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="some-id">
  <div>
    <h3 align="left">vangard</h3>
  </div>
  <ul>
    <li >Rates</li>
    <li >Portfolio</li>
    <li >Cases</li>
  </ul>
  <h3 align="left">Fedility</h3>
  <ul>
    <li >Rates</li>
    <li >Cases</li>
  </ul>
  <h3 align="left">McCoughlah</h3>
  <ul>
    <li >Rates</li>
    <li >Portfolio</li>
    <li >Cases</li>
  </ul>
  <h3 align="left">BrownRock</h3>
  <ul>
    <li >Portfolio</li>
    <li >Cases</li>
  </ul>
</div>

  •  Tags:  
  • Related