Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 the entry divs alphabetically by the content of the child title div.

What I've 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 strip the description divs. Try jsFiddle demo.

How can I sort the divs alphabetically without stripping anything?

like image 496
Henrik Petterson Avatar asked Feb 19 '26 01:02

Henrik Petterson


1 Answers

Your logic is correct, but the issue is you're sorting the .title elements. Instead you need to sort the .entry elements, and then find the .title within the current .entry and perform the comparison on their text values. Try this:

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>
like image 187
Rory McCrossan Avatar answered Feb 21 '26 15:02

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!