stepho stepho - 1 year ago 72
Javascript Question

Count classes in an html document and display it as a number using javascript

How can you simply create a counter that counts a specific class in an html and displays the count in a div e.g.

<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>

<div class="counter">5</div>

Answer Source

You can count the number by using querySelectorAll (or getElementsByTagName) and getting the length property of the returned list of elements:

document.getElementsByClassName("counter")[0].textContent = document.querySelectorAll("ul > li").length;
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>

<div class="counter"></div>

This uses pure JavaScript to get the number of lis and inserts them into the div. Let me break it down:

document.getElementsByClassName("counter")[0]

Get's the first div with class name counter. Next, it access its textContent property, which is the inner text of the element. It then reassigns that to:

document.querySelectorAll("ul > li").length

That searches the document for all elements with the tag li which are immediate children of ul elements. It then get's the length of the returned list of elements.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download