How to count child element using jQuery ?
Last Updated :
27 Apr, 2020
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:
<!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 >
|
Output:
Example 2:
<!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 >
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...