1

Possible Duplicate:
Sort an html list with javascript

I have an :

<ul>
<li>Anytime</li>
<li>Cash is good</li>
<li>Do it now!</li>
</ul>

I constantly add new articles. I want them to be in an alphabetical order without having re-arrange them manually. I have written my site in pure HTML and CSS (I don't get information from a database).

How do I solve this? Do I need Java-script?

Community
  • 1
  • 1
nodesto
  • 505
  • 2
  • 8
  • 24

1 Answers1

5

Based on an example here, check this out:

var ul = $("ul");
var arr = $.makeArray(ul.children("li"));

arr.sort(function(a, b) {
    var textA = +$(a).text();
    var textB = +$(b).text();

    if (textA < textB) return -1;
    if (textA > textB) return 1;

    return 0;
});

ul.empty();

$.each(arr, function() {
    ul.append(this);
});

HTML

<ul>
    <li>Anytime</li>
    <li>Cash is good</li>
    <li>Do it now!</li>
</ul>
Community
  • 1
  • 1
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252