Find Div Length

How to find the number of elements represented in a div ?? I also want to print a list of elements present in the div. I tried this, but it does not work.

<!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 the length, because I dynamically add the element to the div from the j-request, so in the end I want to check which all elements were added successfully.

Thanks,

+4
source share
3 answers

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

+7
source

If you want to process every element that has been dynamically added, you do not need to get the length at all. Instead, you probably just loop, although each one is like this

 $('#main img').each(function(index){ // Your code console.log( $(this).html() ); }); 
+3
source

Many ways to do this.

Decision:

Depending on what you want to count:

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

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

+1
source

All Articles