1

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.

3
  • Which all elements you want to count? Commented Feb 16, 2015 at 19:59
  • It can be done in javascript. Just do .length on the elements that you to count. Commented Feb 16, 2015 at 20:03
  • the how many divs with data-stars 3, how many divs with data-stars 4... and how many elements with data-hoard Full Board and etc.. Commented Feb 16, 2015 at 20:03

2 Answers 2

3

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.