0

I have a list of printed results (divs). Each one contains a child div with text "CLOSE" or "OPEN" what i want is to sort the results so the divs which contain the word "OPEN" be always at the top of the list. How can i do that using jquery ?

<div class="box"><div class="status">CLOSE</div></div>
<div class="box"><div class="status">CLOSE</div></div>
<div class="box"><div class="status">OPEN</div></div>

JSFIDDLE

i think this isn't a duplicate question of THIS because in my fiddle i want to get the list sorted by specific text of a child element and not by attribute "data-sort". Thanks

Designer
  • 875
  • 7
  • 26
  • Possible duplicate of [Sort Divs in Jquery Based on Attribute 'data-sort'?](https://stackoverflow.com/questions/6133723/sort-divs-in-jquery-based-on-attribute-data-sort) – Mario Werner Jul 10 '18 at 21:54

1 Answers1

0

So, you can wrap the elements in a containing div (or other element of your choice), and then use the native sort function in order to sort them. An example:

function sort() {
  // Get your root element
  var root = $("#toSort");
  // Get all your children as standard HTML nodes, and detach them from the DOM
  var elements = root.children(".box").detach();
  // Convert this from a JS object into an array
  var arr = Array.from(elements);
  // Sort your elements
  arr.sort(function(lhs, rhs) {
    var result = rhs.textContent === "OPEN" ? 1 : 0;
    result -= lhs.textContent === "OPEN" ? 1 : 0;
    // Sort works based on result being +ve/-ve/0
    return result;
  });
  // Re-add elements back into the DOM
  root.append(arr);
}
.box {width:85%;margin-bottom:4px;background:#ccc;padding:5px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="sort()">Sort elements</button>
<div id="toSort">
  <div class="box"><div class="status">CLOSE</div></div>
  <div class="box"><div class="status">CLOSE</div></div>
  <div class="box"><div class="status">OPEN</div></div>
  <div class="box"><div class="status">CLOSE</div></div>
  <div class="box"><div class="status">OPEN</div></div>
  <div class="box"><div class="status">CLOSE</div></div>
  <div class="box"><div class="status">OPEN</div></div>
</div>
Andrew
  • 65
  • 9
  • but how can i get them sorted on page load ? – Designer Jul 10 '18 at 22:10
  • why isn't working here? https://jsfiddle.net/1xz62kLa/32/ i did copy/paste your code and sort doesnt work !! – Designer Jul 10 '18 at 22:28
  • 1
    @Designer it seems that jsfiddle puts the function definition within the window.onload function, so it's not accessible to the window scope. Replace the first line with `window.sort = function() {` in this case - see https://jsfiddle.net/1xz62kLa/40/ - you also need to include jQuery, as this is what the initial question requested. The solution I gave though works _mostly_ without jQuery, however. – Andrew Jul 17 '18 at 09:09