Reputation: 453
var count = $("#abc").length;
console.log('Count : ' + count)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="display:none;" id="abc"></div>
I get result = 1. Why is this? The div does not have any children? How can I fix this to get the correct number of children?
Upvotes: 0
Views: 905
Reputation: 1
You have to first find childrens of element using children() method and then calculate no of children`s using length.
so your expression should be
var count = $('#abc').children().length;
console.log('Count: '+count);
Upvotes: 0
Reputation: 101690
Why i get result = 1, but the div not have any child?
Because the .length
property of a jQuery object returns the number of elements in that jQuery object. That number is 1, because you selected that div
.
How to fix it to get correct number of child?
var count = $("#abc").children().length;
Upvotes: 0
Reputation: 337570
You're selecting the #abc
element directly, hence the length property will always be 1
. If you want to get the number of children of the element, use children().length
:
var count = $("#abc").children().length;
console.log('Count:', count);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="display:none;" id="abc"></div>
Upvotes: 2
Reputation: 15555
var count= $("#abc").children().length;
console.log('Count : '+count)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="display:none;" id="abc">
</div>
You are getting the length of the element with id abc
Add children to selector to count child
Upvotes: 2