skip to Main Content

I created a css class for 8 divs, I need to use the each function of jquery to count the divs and show the result in the page’s html, example: “8 divs appear”.

I created a code but it doesn’t work, it doesn’t show the result.

code:

 <script>
    $( ".class" ).each(function( index ) {
      console.log( index + ": " + $( this ).text() );
    });
    </script>

3

Answers


  1. Chosen as BEST ANSWER

    After a few attempts, I managed to solve the problem.

    I created three codes and they worked and gave me the result I wanted. Thanks a lot for the help.

    1.

        var totalPageProducts;
    jQuery('.products-grid .item').each(function(index, value) {
    totalPageProducts = index + 1;
    jQuery('.show-no').html('Showing '+ totalPageProducts +' products');
    });
    

    2.

    jQuery(document).ready(function($) {
        jQuery('.show-no').html('Showing '+ jQuery('.products-grid .item').length +' products');
    });
    

    3.

    jQuery('.show-no').html('Showing '+ jQuery('.products-grid .item').length +' products');
    

  2. if you just want to count them, you can do:
    $('.class').length

    Login or Signup to reply.
  3. From each() method to get whole same class divs index + content or You want to count how many divs has same class then simply use .length.

    Note: Check on Full page. then you can see same class divs count result.

    // Console inded with each div text.
    $('.sameclass').each(function(index){
      console.log(index +':'+ $(this).text());
    });
    
    //Count How many divs has (sameclass) class. 
    $('.result').text($('.sameclass').length);
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    
    <div class="sameclass">Text #1</div>
    <div class="sameclass">Text #2</div>
    <div class="sameclass">Text #3</div>
    <div class="sameclass">Text #4</div>
    <div class="sameclass">Text #5</div>
    <div class="sameclass">Text #6</div>
    <div class="sameclass">Text #7</div>
    <div class="sameclass">Text #8</div>
    <hr>
    <p>Total divs has (sameclass): <strong class="result"></strong></p>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search