How to get the number of children?

I am trying to count how many elements with class .test inside 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 cannot get the correct div number with a class name test.

+4
source share
6 answers

Change the selector as follows:

 $('#testDiv .test').length 

Put space between #testDiv and .test .

$('#testDiv .test') will find direct children #testDiv with class=test .

Full code:

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

Note

$('#testDiv.test') means that you select an element that has both id=testDiv and class=test , like <div id="testDiv" class="test"></div> .

+5
source

Try adding a space between #testDiv and .test

 $('#testDiv .test').length 

You have, as shown below,

 $('#testDiv.test') //- element with ID testDiv and class test //<div id="testDiv" class="test">...</div> 
+4
source

You are looking for an element with the identifier testDiv AND the class test , for example

 <div id="testDiv" class="test"> 

You need

 $('#testDiv .test") ^--- note the space 

instead of this. With a space there will be all nodes with class "test", which are children of node with id testDiv.

+3
source

Try:

 $('#testDiv').children('.test').length; 
+1
source
  • $('#testDiv .test") This will count all immediate descendants - if it is a child of a child, you will not count it.
  • $('#testDiv').find('.test') or just $('#testDiv, .test') will find ALL descendants.
+1
source

Hi, I am writing 3 cases:

Method 1: If .test is a direct child of #testdiv

In this you can use . children

For instance:

 $("#testdiv").children(".test") 

This will give you an array of elements with the class 'test'. In javascript, to find the size of the array, we use the length property. So $ ("# Testdiv"). Children ("test"). Length will do your work.

Method 2: Similarly, to find all elements with class "test" in your #testdiv, you can use . Find callback. This approach should be used if you do not know the nested level of the ".test" element, because it is not optimized. For example: $ ("# Testdiv"). Find ("Test") This will give you an array of elements. Use the same .length thing to find the size of the array.

Method 3: You can also try:

 $("#testdiv .test") 

This will work the same as the method: 2, but it is less optimized.

Your mistake: You tried to use the following syntax

 $("#testdiv.test") 

This selector provides an element with class 'test' and id 'testdiv'.

thanks

+1
source

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


All Articles