JQuery - How to Count Child Elements in Div?

By Hardik Savani July 21, 2023 Category : jQuery

Hi All,

This article goes in detailed on jquery how to count elements in div. we will help you to give example of jquery count elements in div with class.

Here you will learn jquery count number of elements in div. i would like to share with you jquery number of elements in div.

Let's see bellow simple example of count child elements in div using jquery. you can also count specific tag in div using jquery. i will give two example that will help you.

Example: Count "p tag" in Div

<!DOCTYPE html>

<html>

<head>

<title>jquery count number of elements in div - itsolutionstuff.com</title>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

</head>

<body>

<h1>jquery count number of elements in div - itsolutionstuff.com</h1>

<div id="myDiv">

<h1>Hi</h1>

<p>Hello 1</p>

<p>Hello 2</p>

</div>

<button class="btn1">Click Me!</button>

<script>

$(document).ready(function(){

$('.btn1').click(function(){

var elementCount = $('#myDiv p').length;

alert(elementCount);

});

});

</script>

</body>

</html>

Example: Count all tag in Div

<!DOCTYPE html>

<html>

<head>

<title>jquery count number of elements in div - itsolutionstuff.com</title>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

</head>

<body>

<h1>jquery count number of elements in div - itsolutionstuff.com</h1>

<div id="myDiv">

<h1>Hi</h1>

<p>Hello 1</p>

<p>Hello 2</p>

</div>

<button class="btn1">Click Me!</button>

<script>

$(document).ready(function(){

$('.btn1').click(function(){

var elementCount = $('#myDiv *').length;

alert(elementCount);

});

});

</script>

</body>

</html>

I hope it can help you...

Tags :
Shares