How can I count the number of children of a DOM element?

I would like to determine the number of images inside a specific div. I'm pretty sure that I have code to select the elements that I would like to count:

var imageCount = $("#work img").size(); 

And the div itself couldn't be simpler:

<div id="work" class="shown">
<img src="graphics/gallery/001.jpg" />  
<img src="graphics/gallery/002.jpg" />
</div>

But when I ask

alert(imageCount);

It returns 0, not 2! What am I doing wrong? And yes, I am warning inside ready, so I know that the elements are available ...

+3
source share
3 answers
var imgCount = $('#work > img').length

If this does not work, double-check your markup and make sure the elements imgare children.

+3
source

It looks like you are using jQuery. You can do it:

var imageCount = $("#work").children("img").length;
-1
source

- ..

 $("#work").children("img").length

. count-immediate-child-div-elements-using-jquery

-3

Source: https://habr.com/ru/post/1752197/


All Articles