Com And Hosting

You can easily sort your ordered or un-ordered list in the website using jQuery. I have used very simple script which sort the Ordered list alphabetically and I have also did some styling in CSS to display letters instead of number.

Here is my html content –

<ol id="myOL">
    <li>Something </li>
    <li>Zoombie 2</li>
    <li>Tree Lopper</li>
    <li>Anaconda 4</li>
    <li>Peter Papa</li>
    <li>November Rain</li>
    <li>Rain Forest</li>
</ol>

Place the following javascript code in the header section of the page. Assuming you have clear idea about jQuery library and  how it works. If you don’t know much about jQuery then visit the jQuery website for details.

<script type="text/javascript">

$(function () {
    var mylist = $('#myOL');
    var listitems = mylist.children('li').get();
    listitems.sort(function (a, b) {
        return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
    })
    $.each(listitems, function (idx, itm) {
        mylist.append(itm);
    });

});

</script>

Here is some basic CSS code for styling the ordered list –

body {
    font: Arial;
}
ol {
    counter-reset: list;
}
ol li {
    list-style: none;
}
ol li:before {
    content: counter(list, lower-alpha)") ";
    counter-increment: list;
}

When the page rendered it displays like this –

Ol sorting

 

Leave a Reply

Your email address will not be published.