em0tic0n
em0tic0n

Reputation: 290

Count HTML elements with jQuery

I have lots HTML elemts that needs to be counted

<div data-stars="2" data-board="Half Board">STARS 2 / HB</div>
<div data-stars="2" data-board="Half Board">STARS 2 / HB</div>
<div data-stars="4" data-board="Half Board">STARS 4 / HB</div>
<div data-stars="4" data-board="Full Board">STARS 4 / FB</div>
<div data-stars="3" data-board="Half Board">STARS 3 / HB</div>

How can i count the to appear as below

<h4 class="total-found">5</h4>
<h4 class="total-found-3stars">1</h4>
<h4 class="total-found-4stars">2</h4>
<h4 class="total-found-2stars">2</h4>
<h4 class="total-found-HB">4</h4>
<h4 class="total-found-HB">1</h4>

I have tried searching over SO and internet but nothing fits to my needs. Thanks in advance for any advise.

Upvotes: 1

Views: 870

Answers (2)

emmanuel
emmanuel

Reputation: 9615

You should count the .length of attributes.

var two_stars = $('div[data-stars="2"]').length;
var three_stars = $('div[data-stars="3"]').length;
var four_stars = $('div[data-stars="4"]').length;
var five_stars = $('div[data-stars="5"]').length;
var total = two_stars + three_stars + four_stars + five_stars;
$('.total-two').text(two_stars);
$('.total-three').text(three_stars);
$('.total-four').text(four_stars);
$('.total-five').text(five_stars);
$('.total').text(total);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div data-stars="2" data-board="Half Board">STARS 2 / HB</div>
<div data-stars="2" data-board="Half Board">STARS 2 / HB</div>
<div data-stars="4" data-board="Half Board">STARS 4 / HB</div>
<div data-stars="4" data-board="Full Board">STARS 4 / FB</div>
<div data-stars="3" data-board="Half Board">STARS 3 / HB</div>
<br>
Two stars: <span class="total-two"></span><br>
Three stars: <span class="total-three"></span><br>
Four stars: <span class="total-four"></span><br>
Five stars: <span class="total-five"></span><br>
Sum: <span class="total"></span>

Upvotes: 3

Sam
Sam

Reputation: 1

you can loop through any DOM element as follows..

var allElements = document.getElementsByTagName("*");
for (var i=0, max=allElements .length; i < max; i++)
{
    // Do something with the element here
}

Upvotes: 0

Related Questions