Reputation: 93
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>
Upvotes: 2
Views: 1932
Reputation: 57944
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 li
s 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.
Upvotes: 2