Search code examples
javascriptjqueryjquery-eventsdom-manipulation

jQuery sort the DOM based on the numbers


Following is the class which is repeated:

<div class="inner">
          <p> 
                    Text1 
                    <span class="plus"> 25</span>
                    <span class="minus">12</span>
          </p>
</div>



<div class="inner">
              <p> 
                        Text2 
                        <span class="plus"> 205</span>
                        <span class="minus">2</span>
              </p>
    </div>

I have two href tags to act as sort button:

<a href="#" id="pos">Sort by Positive.</a>
<a href="#" id="neg">Sort by Negative.</a>

Through jQuery, how can I re-render the dom, with the <p> sorted based on the button click?

The fiddle is located here.


Solution

  • Something like:

    $("#pos").click(function(e){
      e.preventDefault();
    
      $('.inner').sort(function (a, b) {
        return parseInt($('.plus', a).text(), 10) - parseInt($('.plus', b).text(), 10);
      })
      .appendTo('div.main');
    });
    
    $("#neg").click(function(e){
      e.preventDefault();
    
      $('.inner').sort(function (a, b) {
        return parseInt($('.minus', a).text(), 10) - parseInt($('.minus', b).text(), 10);
      })
      .appendTo('div.main');
    });
    

    http://jsfiddle.net/pHyDm/8/

    Though the two functions are basically the same and could/should probably be refactored a bit.