Number of jQuery DIV

I am trying to count the number of elements under the parent, but this gives me the wrong count. The result should be 2, where when it returns me 4.

My HTML structure:

<div style="overflow: hidden;" id="parentDiv" class="scroll">

<div id="3">
  <table id="t3" class="Table">
    <tbody>
      <tr>
        <td id="b3" class="bY"><table id="inner1" width="100%" cellpadding="3">
            <tbody>
              <tr>
                <td class="code" id="code3" width="172"></td>
                <td class="Num" id="Num3" width="50"></td>
                <td colspan="2" class="Name" id="Name"></td>
              </tr>
              <tr>
                <td class="code" width="172"></td>
                <td>&nbsp;</td>
                <td class="serial" width="110"></td>
                <td class="serial" width="322"></td>
              </tr>
            </tbody>
          </table></td>
      </tr>
    </tbody>
  </table>
</div>

 <div id="4" >
  <table id="t4" class="Table">
    <tbody>
      <tr>
        <td id="b4" class="bY"><table id="inner1" width="100%" cellpadding="3">
            <tbody>
              <tr>
                <td class="code" id="code4" width="172"></td>
                <td class="Num" id="Num4" width="50"></td>
                <td colspan="2" class="Name" id="Name"></td>
              </tr>
              <tr>
                <td class="code" width="172">&nbsp;</td>
                <td>&nbsp;</td>
                <td class="serial" width="110"></td>
                <td class="serial" width="322"></td>
              </tr>
            </tbody>
          </table></td>
      </tr>
    </tbody>
  </table>
</div>

and the code I use to count:

var numofDivs = $("#parentDiv div").size();
alert(numofDivs);

and if I use the following code, the result will be 1 (which is also wrong).

var numofDivs = $("#parentDiv > div").size();
alert(numofDivs);
+3
source share
2 answers

Hi, you should use the children () function

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

The function gives you an array and ten you can get the length.

and in the children function you can specify which tags will be filtered, but you can also leave it empty and it will give you all the children

check API

+6
source

HTML- , .

, , HTML- , . , , :

<div id="parentDiv">
  <div>
    <div></div>
    <div></div>
  </div>
  <p>
    <div>
    </div>
  </p>
</div>

div, , , , div div ,

function countDivs(element) {
  var cnt = 0;
  $(element).children().each(function(){
    cnt += this.tagName === 'DIV' ? 1 : countDivs(this);
  })
  return cnt;
}

$(function(){
  alert(countDivs($('#parentDiv').get(0)));
});
0

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


All Articles