Sorting nested lists

Given is a nested list, with the following markup (and sadly can't be changed at this moment). I want to sort this list (and all nested lists by the 'a'-tag title.) The first div (which is not nested in 'li') should be used to sort the 'ul'-siblings.

Performance is also important, as this list can easly contain more than 100 items, but less than I guess 1000. (I'm not sure if this might become a performance issue)

<ul>
    <div class="bioResult"><a href="">Test</a></div>
</ul>
<ul>
    <li>
        <ul>
            <div class="bioResult"><a href="">C Departmnet</a></div>
            <li>
                <div class="bioResult"><a href="">C</a></div>
            </li>
        </ul>
    </li>
</ul>

I already struggled around and got the nested list sorting done, but I couldn't get my head around the 'ul'-siblings sorting, as it didn't work as I thought it could work. :)

See my fiddle.

Plugins aren't an option at this moment.

Answers:

Answer

Sorting everything is a matter of appending all nodes to their respective parents in alphabetical order.

function uCase(elem) {
    return $.trim( $(elem).text().toUpperCase() )
}
function compareFirstLink(a, b) {
    var A = uCase( $(a).first('a') ),
        B = uCase( $(b).first('a') );       
    return (A > B) ? 1 : -1;
}
$(function () {
    var $sortables = $("ul:has(div:first-child), li:not(.fixedOrder)");
    $sortables.sort(compareFirstLink).each(function () {
        this.parentNode.appendChild(this);
    });
});

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.