How to count child element using jQuery ?

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!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>
      
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>

chevron_right


Output:

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width">
   <title>Count child elements using  jQuery.</title>
   <script src=
    </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>

chevron_right


Output:




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.