stepho stepho - 1 year ago 61
Javascript Question

Count tags of a specific type in an html document and display it as a number using javascript

How can you simply create a counter that counts a specific type of element in an html and displays the count in a div. For example, count the

li
and display the number:

<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