LearnFast.Ninja

jQuery count elements in div

Build div with elements. Call to function that count the elements in the div. Try the working example.

Step 1: Build div with elements. 
 <div id="My_Div" > 
 <div id="Child_1" >Child 1</div> 
 <div id="Child_2" >Child 2</div> 
 <div id="Child_3" >Child 3</div> 
 </div> 
 
Step 2: Call to function that count the elements in the div. 

function count_elements_in_div(Div_Id, Div_Res) {

    var count = $("#" + Div_Id + " > *").size();

    $("#" + Div_Res).html(count);

}

 
The main idea is: 

$("#My_Div > *").size();

 
Complete code: 

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title>jQuery count elements in div </title>

 

    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script>

 

    <script type="text/javascript">

        function count_elements_in_div(Div_Id, Div_Res) {

            var count = $("#" + Div_Id + " > *").size();

            $("#" + Div_Res).html(count);

        }

    </script>

</head>

<body>

    <div id="My_Div">

        <div id="Child_1">Child 1</div>

        <div id="Child_2">Child 2</div>

        <div id="Child_3">Child 3</div>

    </div>

    <input type="button" value="Count the childrens" onclick="count_elements_in_div('My_Div', 'Result');" />

    <div id="Result"></div>

</body>

</html>


Tags

jquery

count