1

I have been looking at the stackoverflow thread:

How may I sort a list alphabetically using jQuery?

but for my scenario, I have the hierachy:

<ul><li><a href="http://www.google.com.au">NAME_TO_SORT_ON</a></li></ul>

Based on this set-up, how can I modify the solution from thread mentioned here to cater for my scenario which has a tag as I would like to sort on all the name found in NAME_TO_SORT_ON?

Thanks.

2
  • If you sort it, it will be an ordered list, not an unordered list... Commented Oct 8, 2009 at 9:41
  • Thanks NickFitz but this is what I am after. I cannot change the tags so require a means to sort an unordered list. Commented Oct 8, 2009 at 14:20

1 Answer 1

1

I would recommend using a jQuery-based solution for this, because once you start getting into multiple DOM levels (e.g. sorting siblings at one level based on the contents of elements at a deeper level) the simple sort mechanism breaks down. It's an extremely rough solution - essentially blowing away the existing HTML and replacing it in raw text mode with other HTML. We can do better by actually shuffling the DOM elements around:

function sort(list, key) {
    $($(list).get().reverse()).each(function(outer) {
        var sorting = this;
        $($(list).get().reverse()).each(function(inner) {
            if($(key, this).text().localeCompare($(key, sorting).text()) > 0) {
                this.parentNode.insertBefore(sorting.parentNode.removeChild(sorting), this);
            }
        });
    });
}

To use it, we pass in a selector to the list and a selector to use to locate the key we want to sort on:

<ul class="toBeSorted">
    <li><a href="...">sort me</a></li>
</ul>

<script type="text/javascript">
    sort('ul.toBeSorted>li', 'a');

    //we want to sort the <li>'s in ul.toBeSorted;
    //and we want to use the text of the first and only <a>
    //in each item as the sort key
</script>
Sign up to request clarification or add additional context in comments.

4 Comments

Rex, tried it out and unfortunately getting an error:object required on the sort() call. Didn't realise but my ul is actually inside a div with id of refmenu. So my new sort call is as follows: sort('#refmenu>ul.platsys>li', 'a'); Is this call correct and any ideas as to what could be wrong? Thanks.
@tonsils you are including the jQuery library before sort() is called?
Surely am Rex. Firstly, am I using the new sort parameters correctly to include div id of refmenu? 2) Any ideas what I could be doing wrong? FYI, I am using jQuery 1.3.2 version.
This works beautifully, please mark as the right answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.