Reputation: 11
i have tried the solutions on this page for counting divs inside parent (class) div. but unfortunately my result is alway displaying the whole number of existing children divs. as the sample follows both of the span tags will output 7.
for better undersanding this is the code html: what is missing? - (i am absolutely greenhorn). thnx.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>count</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div id="content-body" class="clearfix">
<!-- detail div no 1 = 3 items inside -->
<span class="countDiv"></span>
<div class="detail">
<div class="box">
Div item 1
</div>
<div class="box">
Div item 2
</div>
<div class="box">
Div item 3
</div>
</div>
<br /><br />
<!-- detail div no 1 = 4 items inside -->
<span class="countDiv"></span>
<div class="detail">
<div class="box">
Div item 1
</div>
<div class="box">
Div item 2
</div>
<div class="box">
Div item 3
</div>
<div class="box">
Div item 4
</div>
</div>
</div>
<script type="text/javascript">
$('#content-body').each(function() {
var n = $('.detail').children('.box').length;
$(".countDiv").text("There are " + n + " divs inside parent box detail.");
});
</script>
</body>
</html>
Upvotes: 1
Views: 4476
Reputation: 612
Check this fiddle: http://jsfiddle.net/geko/vXcgZ/
Problem is your each, and the
$('.detail').children('.box').length
This selects all .detail elements in your container and all children with .box. Which is a total of 7. You should go through .detail using each() and take count for .box children and modify coresponding countDiv.
Upvotes: 5
Reputation: 225
I don't know why you are trying to count the divs with the same class name. When you are using $('.detail')
it will get all the elements which have the class name "detail" in the page, so you cannot count the specific div with the same name with other divs by this way.
$('#content-body').each(function() {
var n = $('.detail').children('.box').length;
$(".countDiv").text("There are " + n + " divs inside parent box detail.");
});
I think it could be:
$('#content-body .detail').each(function() {
var n = $(this).children('.box').length;
$(this).append("<div>There are " + n + " divs inside parent box detail.</div>");
});
and if you want to count the specific div you should provide different class name.
Upvotes: 1