if you just want to count them, you can do:
$('.class').length
Solution 1 :
Solution 2 :
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>
Solution 3 :
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');
Problem :
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>
Comments
Comment posted by GetSet
Can you post your console log output. It can’t be done here. So u help us out on that part. Your html might be helpful too.
Comment posted by i.stack.imgur.com/JM8zP.png
Here the image of the console log output. [1]:
Comment posted by Pablo Batista
I created a specific class just for these divs, I want my code to count by the css class, I’m locked. 🙁
Comment posted by Yosef Tukachinsky
$('.class').length + ' divs appear'