melonsvk melonsvk - 2 months ago 5
jQuery Question

Jquery: Sort by inner element's attribute

I have following code:

<div>
<div id="1">
<h3>Price: 50</h3>
<span id="price" min-price="50"></span>
</div>
<div id="2">
<h3>Price: 30</h3>
<span id="price" min-price="30"></span>
</div>
<div id="3">
<h3>Price: 40</h3>
<span id="price" min-price="40"></span>
</div>
</div>


I need to sort these 3 divs based on min-price attribute. Is it possible in Jquery? I found
sort()
function, but I was not able to use it correctly. Thank you.

Answer

Try this :

$(document).ready(function() {
     
     $("div[id]").each(function(number,ele) {
         
         $("div[id]").not($(ele)).each(function(index,el){
             
             a = $(ele).find("span").attr("min-price");
             b = $(el).find("span").attr("min-price");
             
             if( parseFloat(a) > parseFloat(b) )
                 $(ele).insertAfter($(el));
             
         })
         
     })
     
 })
<div>
  <div id="1">
    <h3>Price: 50</h3>
    <span id="price" min-price="50"></span>
  </div>
  <div id="2">
    <h3>Price: 30</h3>
    <span id="price" min-price="30"></span>
  </div>
  <div id="3">
    <h3>Price: 40</h3>
    <span id="price" min-price="40"></span>
  </div>
</div>
        
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

Comments