Limiting search scope jQuery -
how limit scope each group sold value reflects numbers group?
jquery:
var sales = (function calculatesales(){ $( "h1 small" ).each(function() { var group = $(this).parent('.group'); var numitems = group.find('.btn').length; var sold = group.find('.btn.hidden').length; $(this).text(sold+" of "+numitems+" sold"); }); return calculatesales; }());
html:
<div class="group"> <h1>title <small>value</small></h1> <div> <a href="#" class="btn"></a> </div> <div> <a href="#" class="btn hidden"></a> </div> </div> <div class="group"> <h1>title <small>value</small></h1> <div> <a href="#" class="btn"></a> </div> <div> <a href="#" class="btn hidden"></a> </div> </div>
var group = $(this).parent('.group');
should var group = $(this).closest('.group');
the .parent() method searches parent node of searching set(small
in case), @ h1
not satisfies given selector won't return anything.
since want @ ancestral tree use .closest()
var sales = (function calculatesales() { $("h1 small").each(function() { var group = $(this).closest('.group'); var numitems = group.find('.btn').length; var sold = group.find('.btn.hidden').length; $(this).text(sold + " of " + numitems + " sold"); }); return calculatesales; }());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="group"> <h1>title <small>value</small></h1> <div> <a href="#" class="btn"></a> </div> <div> <a href="#" class="btn hidden"></a> </div> </div> <div class="group"> <h1>title <small>value</small></h1> <div> <a href="#" class="btn"></a> </div> <div> <a href="#" class="btn hidden"></a> </div> </div>
Comments
Post a Comment