Mr. Mike
Mr. Mike

Reputation: 453

Why i get wrong number of child of div with Javascript?

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

Answers (4)

Amit
Amit

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

JLRishe
JLRishe

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

Rory McCrossan
Rory McCrossan

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

guradio
guradio

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

Related Questions