-1

I need to count the child elements in a <div> with jQuery:

<div id="home">
   <div>..</div>
   <div></div>
</div>

The jQuery code I tried is:

console.log($('#home').length);

But it prints 0.
Anyone can help me?

John Hascall
  • 9,176
  • 6
  • 48
  • 72
Picco
  • 423
  • 2
  • 6
  • 21

5 Answers5

1
$( document ).ready(function() {
    var divLength = $('#home').children().length;
    console.log(divLength);
});
PiraTa
  • 475
  • 2
  • 8
  • 22
1

Are you trying to count the div's inside #home?

If so, try this:

$(document).ready(function() {
    console.log($('#home div').length);
});
rorymorris89
  • 1,144
  • 7
  • 14
0

Try wrapping your code in a document ready function,

$( document ).ready(function() {
    console.log($('#home').length);
});
DevStacker
  • 675
  • 10
  • 23
0

Use * to count all elements in #home like following.

$('#home *').length

If you want to count only direct child the use direct child selector >.

$('#home > *').length
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55
0

After completion of loading of DOM, try this code.

    $('#home').children().length; 
Deepesh kumar Gupta
  • 884
  • 2
  • 11
  • 29