Open In App

How to count all elements within a div using jQuery ?

Last Updated : 07 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will count all elements inside a div element using jQuery. To count all elements inside a div elements, we use find() method and length property.

The find() method is used to find all the descendant elements of the selected element. It will traverse all the way down to the last leaf of the selected element in the DOM tree.

Syntax:

$(selector).find()

Here selector is the selected elements of which all the descendant elements are going to be found.

The length property is used to count number of the elements of the jQuery object.

Syntax:

$(selector).length

Note: Here selector is the object whose length is to be calculated.

Example:

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
   
    <!-- Import jQuery cdn library -->
    <script src=
    </script>
 
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                var count = $(".GFG").find("*").length;
                $("p").after("<h3>Total Div Elements: "
                    + count);
            });
        });
    </script>
</head>
 
<body style="text-align: center;">
    <h1 style="color: green;">
        GeeksforGeeks
    </h1>
 
    <h3>
        How to count all elements
        within a div using jQuery?
    </h3>
   
    <div class="GFG">
        <p>
            GeeksforGeeks computer
            science portal
        </p>
 
        <input type="text">
    </div><br>
   
    <button>Click Here!</button>
</body>
 
</html>


Output:

Before Click Button:

After Click Button:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads