Chris
Chris

Reputation: 2488

Ordering a complex unordered list with javascript

I am looking for a way to sort a fairly complicated html unordered list using either standard javascript or jQuery.

Please view the HTML, the order needs to be alphabetical and based on the HTML found inside the ".keywordType span value" but needs to construct the order of the top level li (with the unique keyword_xxx). I've just pasted 2 of the list items out of dozens.

<ul class="keywords">
    <li id="keyword_185">
        <div class="icon_keyword"></div>
        <input type="hidden" class="keywordLabel" value="More opening hours">
        <div class="data-wrapper">
            <div class="keywordType">
                <span class="oh">Payment methods</span>
            </div>
            <div class="keywordValue">
                <span id="keyword_185" class="oh">Credit Card, PayPal</span>
            </div>
        </div>
        <a class="edit" title="Edit keywords"></a>
        <a class="delete" title="Delete keywords"></a>
    </li>
    <li id="keyword_192">
        <div class="icon_keyword"></div>
        <input type="hidden" class="keywordLabel" value="Monday to Friday: 8:30am to 6:30pm Saturday: 9pm to 6:30pm Sunday: 10 - 4pm">
        <div class="data-wrapper">
            <div class="keywordType">
                <span class="oh">Opening Hours</span>
            </div>
            <div class="keywordValue">
                <span id="keyword_192" class="oh">Monday to Friday: 8:30am to 6:30pm<br>Saturday: 9pm to 6:30pm<br>Sunday: 10 - 4pm</span>
            </div>
        </div>
        <a class="edit" title="Edit keywords"></a>
        <a class="delete" title="Delete keywords"></a>
    </li>
</ul>

Thanks

Upvotes: 2

Views: 1103

Answers (3)

katspaugh
katspaugh

Reputation: 17899

var list = $('ul.keywords');
var listItems = $('li', list);

listItems.sort(function (a, b) {
    return $(a).text() > $(b).text() ? 1 : -1;
});

list.append(listItems);

You can sort the list of elements (jQuery objects have all the methods of Array, including Array.prototype.sort).

In the comparison function simply compare the text content of the list items. Individual letters will be subsequently compared according to their position in the alphabet (Unicode table, actually). For example, k > a is true.

Finally, just re-append the items to the list.

Demo: http://jsbin.com/igesic

Upvotes: 4

chim
chim

Reputation: 8573

Does this help?

var arr;
$('.keyword span').each( function( i, el){
    arr[i] = $(el).text();
});
arr.sort();

I tested it on this question page, the code below orders the list of related questions in the right hand col.

var arr;
$('.question-hyperlink').each( function( i, el){
    arr[i] = $(el).text();
});
arr.sort();

Upvotes: 0

ShankarSangoli
ShankarSangoli

Reputation: 69915

Take a look at this, it exactly matches your requirement.

http://james.padolsey.com/javascript/sorting-elements-with-jquery/

Upvotes: 2

Related Questions