JQuery Sort Divs by child divs

html, javascript, jquery, sorting

Solution

You have to make a little change to html like following:

<div id="container">
<div class="item">
    <div class="genre">Classical</div>
    <div class="name">Alpha</div>
    <div class="location">London</div>
</div>

<div class="item">
    <div class="genre">Blues</div>
    <div class="name">Bravo</div>
    <div class="location">New York</div>
</div>

<div class="item">
    <div class="genre">Pop</div>
    <div class="name">Charlie</div>
    <div class="location">Paris</div>
</div>
</div>
<div class="buttons">
<a href="" id="genre">Sort by Genre</a>
<a href="" id="name">Sort by Name</a>
<a href="" id="location">Sort by Location</a>
</div>

jQuery

function sorting(tag) {
    var items = $('div.item').sort(function(a, b) {
        var txt1 = $.trim($('div.' + tag, a).text()),
            txt2 = $.trim($('div.' + tag, b).text());
        if (txt1 > txt2) return 1;
        else return -1;
    });
    return items;
}
$('.buttons a').on('click', function(e) {
    e.preventDefault();
    $('div#container').html(sorting(this.id));
});

Working Sample

Problem

I have the following list of divs and I'd like to be able to sort them using Javascript / JQuery. ``` <div class="item"> <div class="genre">Classical</div> <div class="name">Alpha</div> <div class="location">London</div> </div> <div class="item"> <div class="genre">Blues</div> <div class="name">Bravo</div> <div class="location">New York</div> </div> <div class="item"> <div class="genre">Pop</div> <div class="name">Charlie</div> <div class="location">Paris</div> </div> <div class="buttons"> <a href="">Sort by Genre</a> <a href="">Sort by Name</a> <a href="">Sort by Location</a> </div> ``` I'd like to be able to sort the items by their Genre/Name/Location alphabetically. Example: If Sort by Genre was clicked, it would sort the items in 0-9 A-Z by Genre. If any of you have any tips it would greatly be appreciated. Cheers :)

Original source