Reputation: 20882
I have the following DOM Structure. Each 'contactsBodyMainDisplayMemberContainerDIV' shows a member photo, name etc.
I need to be able to re-order these ContainerDIV's by the H2 Username A to Z.
So the below would need to move the 'contactsBodyMainDisplayMemberContainerDIV' pieces of DOM so it's ordered Adam, Bob, Eric. Note: I need to move the whole piece of DOM for each user.
<div id="contactsBodyMainContainerDIV">
<div class="contactsBodyMainDisplayMemberContainerDIV">
<div class="contactsBodyMainDisplayMemberWrapperDIV">
<h2 class="contactsBodyMainDisplayMemberUserNameH2">Eric</h2>
</div>
</div>
<div class="contactsBodyMainDisplayMemberContainerDIV">
<div class="contactsBodyMainDisplayMemberWrapperDIV">
<h2 class="contactsBodyMainDisplayMemberUserNameH2">Adam</h2>
</div>
</div>
<div class="contactsBodyMainDisplayMemberContainerDIV">
<div class="contactsBodyMainDisplayMemberWrapperDIV">
<h2 class="contactsBodyMainDisplayMemberUserNameH2">Bob</h2>
</div>
</div>
</div>
I'm unsure how to do this.
Note: it need this function as members will be added on the fly.
Any advise on how to achieve this?
Upvotes: 1
Views: 68
Reputation: 7997
I'd create an option list, which then is easy to sort:
markup:
<ul id="my_list">
<option value="Eric">Eric</option>
<option value="Adam">Adam</option>
<option value="Bob">Bob</option>
</ul>
javascript:
$("#my_list").html($("#my_list option").sort(function (a, b) {
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
}))
here is the fiddle: http://jsfiddle.net/zRA5b/1/
note: you can obviously stuff all your div's into that <option>
tags: check here: http://jsfiddle.net/zRA5b/2/
edit: you can also sort by option value (which might come in handy if you want to sort by some other database value, like age or lastname, etc.) using:
$("#my_list").html($("#my_list option").sort(function (a, b) {
return a.value== b.value? 0 : a.value< b.value? -1 : 1
}))
Upvotes: 2
Reputation: 488
Hope this code helps
var sorted = $('.contactsBodyMainDisplayMemberContainerDIV').sort(function(a,b){
return $(a).find('.contactsBodyMainDisplayMemberUserNameH2').text() < $(b).find('.contactsBodyMainDisplayMemberUserNameH2').text()) ? 1 : -1;
});
$('. contactsBodyMainContainerDIV').html(sorted);
Upvotes: 2