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.
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');
}
$('#testDiv.test')
means you are selection some element which has both id=testDiv
and class=test
like <div id="testDiv" class="test"></div>
.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With