Open In App

How to count child element using jQuery ?

Last Updated : 27 Apr, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report
It is very simple to count the number of child elements in the HTML file using jQuery. For example: If you have a parent element consisting of many children elements then you can use .length or.children().length method as given below. Syntax:
var len=$("#parentID").length;
or
var count = $("#parentId").children().length;
Example 1: html
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Count child elements using Jquery</title>
    <meta name="viewport" 
          content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="">
</head>

<body>
    <div id="parentID">
        <p>Red</p>
        <p>White</p>
        <p>Green</p>
        <p>Black</p>
        <p>Blue</p>
        <p>Orange</p>
    </div>
    
    <script src="https://code.jquery.com/jquery-3.5.0.min.js"
integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" 
        crossorigin="anonymous">
    </script>

    <script>
             
        // Here we count the child element in parentID
        var count = $("#parentID p").length;
        document.writeln(count);
    </script>
</body>

</html>
Output: Example 2: html
<!DOCTYPE html>
<html>

<head>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width">
   <title>Count child elements using  jQuery.</title>
   <script src=
      "https://code.jquery.com/jquery-3.4.1.js">
    </script>
</head>

<body>
   <div id="parentId">
   <ul>
      <li>1 child</li>
      <li>2 child</li>
      <li>3 child</li>
      <li>4 child</li>
      <li>5 child</li>
    </ul>
    </div>
    <script>
         var count = $("#parentId ul").children().length;
         document.writeln(count);
    </script>
</body>

</html>
Output:

Next Article

Similar Reads