DEV Community

Paramanantham Harrison
Paramanantham Harrison

Posted on • Originally published at learnwithparam.com on

5 1

Vanilla JS equivalent for counting number of child elements using className

Sometimes, we learn lot of bigger things but miss on small learnings. I want to create small posts on vanilla JS to do things without libraries or frameworks on simple pages.

It is very easy to count number of elements using jquery. First we will see it in jQuery and then on vanilla JS.

<ul>
  <li class="li-node">Children 1</li>
  <li class="li-node">Children 2</li>
  <li class="li-node">Children 3</li>
  <li class="li-node">Children 4</li>
  <li class="li-node">Children 5</li>
</ul>
Enter fullscreen mode Exit fullscreen mode

Count using jQuery

$('.li-node').length;
Enter fullscreen mode Exit fullscreen mode

Count using Vanilla JS

document.querySelectorAll('.li-node').length;
Enter fullscreen mode Exit fullscreen mode

document.querySelectorAll select all the elements with class name and returns an array of html element, then we can use the array length property to find the count.

Hope you learned a simple trick in vanilla JS 😎

Neon image

Set up a Neon project in seconds and connect from a Next.js application

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

Top comments (1)

Collapse
 
pappychulow profile image
pappy🇨🇦

i need one that counts it as it is been added to the dom

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Value this insightful article and join the thriving DEV Community. Developers of every skill level are encouraged to contribute and expand our collective knowledge.

A simple “thank you” can uplift someone’s spirits. Leave your appreciation in the comments!

On DEV, exchanging expertise lightens our path and reinforces our bonds. Enjoyed the read? A quick note of thanks to the author means a lot.

Okay