Search code examples
javascriptjquerysortinginnerhtml

javascript sort DOM element alphabetically using innerHTML


I'm loading a html from a JavaScript array with innerHTML. I'd like to sort it alphabetically, if I click an anchor tag. How can I do that? My code is pretty complex, but the for the question, this is the important part:

<script>
var locations = [['image.png', 'title', 'category', 'city', 'phone', 'address,
zip', 'lat', 'long', '', 'img.png', 'link', '0']];

var load_list_html = "";    

  load_list_html += '<div data-position="'+
    locations[i][6]+
    ', '+
    locations[i][7]+
    '" id="maplist" class="map-list-box" data-cat="'+
    locations[i][2]+
    '"><img class="list-view-img pull-left" src="'+
   locations[i][9]+
   '"><h3><a class="list-view-title" href="'+
   locations[i][10]+
   '">'+
  locations[i][1]+
  '</a></h3><div id="list-rate" class="rateit" data-rateit-value="'+
  locations[i][11]+
  '" data-rateit-ispreset="true" data-rateit-readonly="true">'+
  '</div><p class="list-text">'+
   locations[i][8]+
  '</p><span class="list-address">'+
  locations[i][5]+
  ', <strong>'+
  locations[i][3]+
  '</strong>'+
  '</span><br><span class="list-phone">'+
  locations[i][4]+
  '</span></div><!--map-list-box-->';

document.getElementById("load_list").innerHTML = load_list_html;
</script>

<body>
<div id="load_list"></div> 
Order by<a id="alphBnt">Alphabetically ordered</a>
</body>

How can I order the elements alphabetically by title, (#load list h3 a), I've tried the sort function, but it didn't work. What is the best way to achieve that?


Solution

  • Javascript arrays have an inbuilt function for sorting - Array.sort. In the case of arrays of arrays the they will be sorted by the first element of each child array. To sort by another element in the child array you can supply a compare function -

    $(document).ready(function() {
      var list = [
        [1, "b"],
        [2, "c"],
        [3, "a"]
      ];
      $("#originalresults").text(list.join(','));
      list.sort(function(a, b) {
        if (a[1] > b[1])
          return 1;
        if (a[1] < b[1])
          return -1;
        return 0;
      });
      $("#sortedresults").text(list.join(','));
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="originalresults">
    </div>
    <div id="sortedresults">
    </div>

    So in your case you would want to do something like -

    $("#alphBnt").click(function(){
        locations.sort(function(a, b) {
          if (a[1] > b[1])
            return 1;
          if (a[1] < b[1])
            return -1;
          return 0;
        });
        $("#load_list").clear();
        ........ generate your load_list_html using the code from your question
        $("#load_list").html(load_list_html);
    });
    

    EDIT:

    OK, I've re-read your question and it looks like you may be looking for a way to sort your HTML after it has been rendered. If so you should be able to do something like this -

    $(document).ready(function() {
      $("#sorter").click(function() {
        var $sections = $("#container").children().detach();
        $sections.sort(function(a, b) {
          if ($(a).find("h5 span").text() > $(b).find("h5 span").text()) return 1;
          if ($(a).find("h5 span").text() < $(b).find("h5 span").text()) return -1;
          return 0;
        });
        $("#container").append($sections);
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="container">
      <section>
        <h5>
          <span>D</span>
        </h5>
        <p>
          Something about "D"....
        </p>
        <p>
          Something else
        </p>
      </section>
      <section>
        <h5>
          <span>A</span>
        </h5>
        <p>
          The letter "A" is the first letter of the alphabet.
        </p>
        <p>
          Something else
        </p>
      </section>
      <section>
        <h5>
          <span>C</span>
        </h5>
        <p>
          "C" is the first letter of many words.
        </p>
        <p>
          Something else
        </p>
      </section>
      <section>
        <h5>
          <span>B</span>
        </h5>
        <p>
          The word bee starts with the letter "B".
        </p>
        <p>
          Something else
        </p>
      </section>
    </div>
    <button id="sorter">Sort Them!</button>