LearnFast.Ninja

jQuery count children of element

Build div with elements. Call to function that count the elements in the chosen element. The main idea is to count the size of children. Try the complete code 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 chosen element. 

function count_elements_in_div(Elm_Id, Div_Res) {

    var count = $("#" + Elm_Id).children().size();

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

}

 
The main idea is: 

$("#My_Div").children().size();

 
Complete code: 

<html>

<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(Elm_Id, Div_Res) {

            var count = $("#" + Elm_Id).children().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