stepho stepho - 2 months ago 5
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

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.