Sort nested divs alphabetically
I have the following div layout:
<div class="container">
<div class="entry">
<div class="title">World</div>
<div class="description">text1</div>
</div>
<div class="entry">
<div class="title">hello</div>
<div class="description">text2</div>
</div>
<div class="entry">
<div class="title">Lorem</div>
<div class="description">text3</div>
</div>
</div>
I want to sort a div entry
alphabetically by the content of the child title
div.
What I have tried so far
This will sort it alphabetically:
var alphabeticallyOrderedDivs = $('.title').sort(function(a, b) {
return String.prototype.localeCompare.call($(a).text().toLowerCase(), $(b).text().toLowerCase());
});
var container = $(".container");
container.detach().empty().append(alphabeticallyOrderedDivs);
$('body').append(container);
But it will split the div description
. Try the jsFiddle demo .
How can I sort the divs alphabetically without stripping anything?
source to share
Your logic is correct, but the problem is you are sorting the items .title
. Instead, you need to sort the elements .entry
and then find .title
in the current one .entry
and compare their text values. Try the following:
var alphabeticallyOrderedDivs = $('.entry').sort(function(a, b) {
var $aTitle = $(a).find('.title'), $bTitle = $(b).find('.title');
return String.prototype.localeCompare.call($aTitle.text().toLowerCase(), $bTitle.text().toLowerCase());
});
var container = $(".container");
container.detach().empty().append(alphabeticallyOrderedDivs);
$('body').append(container);
.entry {
border: 1px solid #CCC;
padding: 5px;
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<div class="container">
<div class="entry">
<div class="title">World</div>
<div class="description">text1</div>
</div>
<div class="entry">
<div class="title">hello</div>
<div class="description">text2</div>
</div>
<div class="entry">
<div class="title">Lorem</div>
<div class="description">text3</div>
</div>
</div>
source to share
How can I sort the divs alphabetically without stripping anything?
Sorting the correct items?
Why are you sorting .title
if, as you said, the elements .entry
are what you really want to sort?
var alphabeticallyOrderedDivs = $('.entry').sort(function(a, b) {
return String.prototype.localeCompare.call(
$(a).find('.title').text().toLowerCase(),
$(b).find('.title').text().toLowerCase());
});
source to share
You just need to take the parent with you when sorting. Then you look for the child after which you want to sort:
var alphabeticallyOrderedDivs = $('.entry').sort(function(a, b) {
return String.prototype.localeCompare.call($(a).find("div.title").text().toLowerCase(), $(b).find("div.title").text().toLowerCase());
});
source to share
All Articles