Online Snippets Library

Count the number of div's inside a div using jQuery

We can count the number of div's inside a div by using parent > child selector of jQuery. parent > child selector selects all direct child elements of the specified element.

Syntax

("parent > child")

Example

HTML
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"> </script>
<title>Count the number of div's inside a div using jQuery</title>
<style type="text/css">
.mainborder{border:1px solid;height:150px;padding:5px;}
.innerborder{border:1px solid;height:20px;padding:5px;}
</style>
</head>
<button id="count">Count Div</button>
<span id="show"></span>
<div id="mainDiv" class="mainborder">Main div
<div id="innerDiv1" class="innerborder">Inner div</div>
<div id="innerDiv2" class="innerborder">Inner div</div>
<div id="innerDiv3" class="innerborder">Inner div</div>
<div id="innerDiv4" class="innerborder">Inner div</div>
</div>
</html>
Javascript
$(document).ready(function(){
$("#count").click(function(){
var totalCount=$("#mainDiv > div").length;
$("#show").html(totalCount);
});
});