Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the number of child elements?

Tags:

jquery

I am trying to count how many element with the class .test within my div. I have

<div id='testDiv'>ddd 
   <div class='test'> 111<div> another div </div></div>
   <div class='test'> 222</div>
   <div class='test'> 333</div>
   more...
</div>

My jQuery:

if($('#testDiv.test').length>5){
   alert('haha');
}

I can't seem to get the correct number of div with the class name test.

like image 580
Rouge Avatar asked Dec 07 '22 12:12

Rouge


2 Answers

Change the selector like following:

$('#testDiv .test').length

Put an space between #testDiv and .test.

$('#testDiv .test') will find out the direct children of #testDiv who has class=test.

Full Code:

if( $('#testDiv .test').length > 5 ){
   alert('haha');
}

Note

$('#testDiv.test') means you are selection some element which has both id=testDiv and class=test like <div id="testDiv" class="test"></div>.

like image 189
thecodeparadox Avatar answered Dec 11 '22 10:12

thecodeparadox


Try adding a space between #testDiv and .test

$('#testDiv .test').length

What you have is like below,

$('#testDiv.test') //- element with ID testDiv and class test  
//<div id="testDiv" class="test">...</div>
like image 24
Selvakumar Arumugam Avatar answered Dec 11 '22 11:12

Selvakumar Arumugam