5

How to find No. of Elements Present in div?? also i want to print list of Element present in div . I have tried this but it is not working ..

<!DOCTYPE html>
<html>
<head>
<title> Div Length</title>
<script type="text/javascript" src="js/jquery-1.6.2.min.js">

</script>
<script>
    $(function ()
    {
    alert(' Elements are ' +$('#main').length);

    }
    )
</script> 
</head> 
<body>

<div id="main">

<img src="images/thumb1.jpg"; height="30" width="30" />
<img src="images/thumb2.jpg"; height="30" width="30"/>
<img src="images/thumb3.jpg"; height="30" width="30"/>
<img src="images/thumb4.jpg"; height="30" width="30"/>
<div id="main1">

</div>

<div id="main2">

</div>


</div>
</body> 
</html>

I need to find length because i am dynamical adding element in div from j query so at the end i want to check what are all elements that has been added successfully .

Thanks,

anam
  • 3,905
  • 16
  • 45
  • 85
  • see the following links http://stackoverflow.com/questions/250688/count-immediate-child-div-elements-using-jquery http://stackoverflow.com/questions/4291151/jquery-count-child-elements – Atish Kumar Dipongkor Apr 18 '13 at 05:34

3 Answers3

9

$("div#main").children().length

Andrew Klatzke
  • 554
  • 2
  • 4
  • 15
3

If you want to process each item which has been dynamically added you don't need to get the lenght at all. Instead you probably just what to loop though each one like this

$('#main img').each(function(index){
  // Your code
  console.log( $(this).html() );
});
Daveo
  • 19,018
  • 10
  • 48
  • 71
2

Many ways to do that.

A solution :

Depending on what you want to count :

$('#main div').length return the number of div in main div

$('#main img').length return the number of images in main div

sdespont
  • 13,915
  • 9
  • 56
  • 97