Sorting elements on page Alphabetically

I am trying to sort the text content of divs on a page on button click.

JS Fiddle Link:
https://jsfiddle.net/Jamescodes/4k7xonqv/188/

HTML

  <button id="myBtn">
    Sort Em!
  </button>

  <div class="red sortme">Steve</div>
  <div class="orange sortme">Dex</div>
  <div class="yellow sortme">Bob</div>
  <div style="color: green;" class="sortme">Colin</div>
  <div class="cyan sortme">James</div>
  <div class="blue sortme">Margie</div>
  <div class="purple sortme">Albert</div>

CSS

.red {
  color: red;
}

.orange {
  color: orange;
}

.yellow {
  color: yellow;
}

.cyan {
  color: cyan;
}

.blue {
  color: blue;
}

.purple {
  color: purple;
}

div.sortme {
  text-align: center;
  padding: 2px;
  max-width: 5rem;
  background-color: hsl(0, 0%, 0%, 0.85);
  border-radius: 5px;
}

button {
  margin: 5px;
  padding: 5px;
  border-radius: 5px;
}

JavaScript

function sortThem(s) {
  console.log('sorting');
  Array.prototype.slice.call(document.body.querySelectorAll(s)).sort(function sort(ea, eb) {
    var a = ea.textContent.trim();
    var b = eb.textContent.trim();
    console.log(a, b);
    if (a.textContent < b.textContent) return -1;
    if (a.textContent > b.textContent) return 1;
    return 0;
  }).forEach(function(div) {
    div.parentElement.appendChild(div);
  });
}
// call it like this
document.getElementById("myBtn").addEventListener("click", function() {
  sortThem('div.sortme')
});

the divs are not being sorted as i would expect them to be when i call the function on click. can someone help me understand why?

107 thoughts on “Sorting elements on page Alphabetically”

  1. therapie comportementale et cognitive roanne therapie de couple vaud , pharmacie pomies aix en provence pharmacie jean beaulieu tring jonction , [url=https://kit.co/storna/tadacip-prix-sans-ordonnance-tadacip-pharmacie-canada#]Acheter Tadacip 20 mg pas cher[/url] pharmacie 14 juillet amiens [url=https://kit.co/packri/brand-cialis-sans-ordonnance-belgique-brand-cialis-prix-sans-ordonnance#]Brand Cialis pharmacie Belgique[/url] , pharmacie auchan nord therapie de couple jette , pharmacie veterinaire boulogne billancourt. therapies breves integratives pharmacie orthopedie boulogne billancourt [url=https://kit.co/anor/quibron-t-sans-ordonnance-quebec-quibron-t-prix-sans-ordonnance#]Quibron-t livraison QuГ©bec[/url] , pharmacie amiens maison de la culture. therapie de couple zurich, pharmacie principale bordeaux pharmacie de garde aujourd’hui perpignan . pharmacie leclerc gueret, pharmacie lafayette amiens telephone pharmacie verte colline aix en provence therapy couples interventions .

    Reply

Leave a Comment