Sorting lists with Element.sortBySelector

Author: Moritz Stuhlmann, May 2008

Imagine this simple Markup

<ul id="friends">
	<li>
		<h1>Mike</h1>
		<p>Age <span class="age">31</span></p>
	</li>
	<li>
		<h1>Anna</h1>
		<p>Age <span class="age">25</span></p>
	</li>
	<li>
		<h1>Steve</h1>
		<p>He will be <span class="age">29</span> next monday.</p>
	</li>
</ul>

Now sort the list

By name?

$("friends").sortBySelector("H1");

By age?

$("friends").sortBySelector("SPAN.age");

Try it out!

How is it done?

sortBySelector(element, selector[, options]) -> HTMLElement

Some more features needed?

Reverse direction

$("friends").sortBySelector("SPAN.age", {reverse: true});

Set the index

Example: If you have two H1-tags in your markup and you need to sort by the second tag, simply set the index (start counting at 0).

$("friends").sortBySelector("H1", {index: 1});

Use any CSS selector

$("foo").sortBySelector("A.more SPAN.info");

Chain other methods

$("foo").sortBySelector("H1").setOpacity(0.5);

What about dates?

markup with <span class="date">2008/5/1</span> works fine

Download

Use it and share it. This code is absolutely free and can be used in any project. Please do not delete the copyright information in the javascript file.

Have fun!

Get the Prototype extension here.