0

I am creating unordered lists dynamically. This creates an output similar to this:

<ul>
    <li>item 1</li>
    <li>item 2</li>
    <li>item 3</li>
        <ul>
            <li>Item 3.1</li>
            <li>Item 3.2</li>
            <li>Item 3.3</li>
        </ul>
    <li>item 4</li>
    <li>Item 5</li>
        <ul>
            <li>Item 5.1</li>
            <li>Item 5.2</li>
            <li>Item 5.3</li>
        </ul>
    <li>item 6</li>
</ul>

I would like to be able to sort through them, after they are created, so that any item that has a sublist(for example item 3 & item 5) will go to the top of the list, for output like this:

<ul>
    <li>item 3</li>
        <ul>
            <li>Item 3.1</li>
            <li>Item 3.2</li>
            <li>Item 3.3</li>
        </ul>
    <li>Item 5</li>
        <ul>
            <li>Item 5.1</li>
            <li>Item 5.2</li>
            <li>Item 5.3</li>
        </ul>
    <li>item 1</li>
    <li>item 2</li>
    <li>item 4</li> 
    <li>item 6</li>
</ul>

I am thinking I can do this with jQuery or the javascript .sort() method but I'm not sure where to go with it. Any advice?

NiteTrip
  • 198
  • 1
  • 1
  • 10
  • 2
    Tinysort may definitely help you. http://tinysort.sjeiti.com/ – Jeremy Thille Feb 17 '15 at 16:04
  • 6
    Is this even valid HTML? Shouldn't the second unordered list be a child of the `li` element? According to this stackoverflow answer, you should change your HTML: http://stackoverflow.com/questions/5899337/proper-way-to-make-html-nested-list – thatidiotguy Feb 17 '15 at 16:06
  • thatidiotguy - I have seen it go both ways in my research and this is the way I decided on. It's not set in stone and is a very easy switch to make the
      a child of the
    • . From the upvotes you have it looks like others agree with you so I will change it. My question still remains.
    – NiteTrip Feb 17 '15 at 16:15

1 Answers1

4

Firstly you should put your sublists inside their parent element and give a class to your list, like this:

<ul class="autoReorder">
   <li>item 1</li>
   <li>item 2</li>
   <li>item 3
      <ul>
         <li>Item 3.1</li>
         <li>Item 3.2</li>
         <li>Item 3.3</li>
      </ul>
   </li>
   <li>item 4</li>
   <li>Item 5
      <ul>
         <li>Item 5.1</li>
         <li>Item 5.2</li>
         <li>Item 5.3</li>
      </ul>
   </li>
   <li>item 6</li>
</ul>

Then in jQuery here is your solution:

$(document).ready(function(){
   $('ul.autoReorder').find('li ul').parent().prependTo('ul.autoReorder');
});
JBA
  • 2,889
  • 1
  • 21
  • 38