Home > Blockchain >  Invert count for children inside a div
Invert count for children inside a div

Time:09-22

I'm using the next function to count every item inside a div and echo the index number for each.

Is there a way to achieve the exact same but starting from the biggest number to the smallest? Sort of flip what's in here

Thanks in advance

$(function() {
  $(".grid").each(function() {

      $(this).find('.num').each(function(i) {
      $(this).text(  i);
      $(this).text(function (i, n) {
   var result = Number(n)   0;
   if ( result < 10 ) {
       return "0"   result   ".";
   } else {
       return result   ".";
   }
      });
    });
  });
});

CodePudding user response:

One way to achieve this would be to implement the native array reverse() method as a jQuery method, credit to this answer, in order to reverse the order of the elements before you iterate through them.

Also note that your text() logic is much more complicated than it needs to be. You're setting a value which is immediately overwritten, adding 0 for no purpose and converting values which are already numerical to Number. You can simply use i directly and use slice() to pad a leading 0 to it.

With all that said, try this:

jQuery.fn.reverse = [].reverse;

jQuery($ => {
  $('.grid').each((i, el) => {
    $(el).find('.num').reverse().text(i => `00${i   1}.`.slice(-3));
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="grid">
  <span class="num"></span>
  <span class="num"></span>
  <span class="num"></span>
  <span class="num"></span>
  <span class="num"></span>
  <span class="num"></span>
  <span class="num"></span>
  <span class="num"></span>
  <span class="num"></span>
  <span class="num"></span>
</div>

<div class="grid">
  <span class="num"></span>
  <span class="num"></span>
  <span class="num"></span>
  <span class="num"></span>
  <span class="num"></span>
  <span class="num"></span>
  <span class="num"></span>
  <span class="num"></span>
  <span class="num"></span>
  <span class="num"></span>
</div>

  • Related