1

I want to sort my divs based on the classname, here's what I have so far:

<div id="container">
    <div class="blue">1</div>
    <div class="red">2</div>
    <div class="red">3</div>
    <div class="blue">4</div>
    <div class="blue">5</div>
    <div class="red">6</div>
    <div class="blue">7</div>
</div>

var elem = $('#container').find('div').sort(sortMe);

function sortMe(a, b) {
    return a.className < b.className;
}
$('#container').append(elem);

.red {
    color:red;
}

.blue{
    color:blue;
}

https://jsfiddle.net/bekvLhm7/

Based on this I would expect my output to look like:

2
3
6
1
4
5
7

But even after running the code it doesn't do anything. What am I doing wrong?

1
  • return a.toLocaleCompare(b); Commented Mar 31, 2020 at 0:42

1 Answer 1

2

You need to return 1 or -1 in the sorting comparator:

var elem = $('#container').find('div').sort(sortMe);

function sortMe(a, b) {
  return a.className < b.className ? 1 : -1;
}

$('#container').append("<br/>");
$('#container').append(elem.clone());
.red {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
  <div>1</div>
  <div class="red">2</div>
  <div class="red">3</div>
  <div>4</div>
  <div>5</div>
  <div class="red">6</div>
  <div>7</div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.