简体   繁体   中英

Sort unordered list with Javascript / jQuery

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?

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');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM