JSFiddle - React, Tailwind, and code Playground

by robert_schutt

HTML

<ul>
  <li>Apples</li>
  <li>Bananas</li>
  <li>Grapes</li>
  <li>Peaches</li>
  <li>Pears</li>
  <li>Watermellon</li>
 </ul>
 <ul>
  <li>Apples</li>
  <li>Bananas</li>
  <li>Grapes</li>
  <li>Peaches</li>
  <li>Pears</li>
  <li>Watermellon</li>
 </ul>
 <div>
  <span>d</span>
  <span>f</span>
  <span>e</span>
  <span>b</span>
  <span>c</span>
  <span style="color: yellow;">a</span>
 </div>

CSS

ul, div {
  float: left;
  margin: 10px;
}
span {
  display: block;
  padding: 2px 6px;
}

JavaScript

$.fn.sortChildren = function() {
	return $(this).each(function(i,ul){
    $(ul).children().sort(function(a,b){
      return $(a).text() > $(b).text();
    }).each(function(idx,obj){
      // move each element to the end in order
      $(ul).append($(obj));
    });
  });
};

// add item to the first list
$('ul:nth-child(1)').append('<li>Mangos</li>');
// add item to the second list and show that css is preserved
$('ul:nth-child(2)').append($('<li>Oranges</li>').css('color', 'orange'));
// call the function and show that function chaining is supported
$('ul, div').sortChildren().css('background-color', 'lightblue');