Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery DIV count

I am trying to count the number of elements under a parent but its giving me an incorrect count. The result should be 2, where as its returning me 4.

My HTML structure is:

<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 am using to count is:

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

and if I am using the following code, the result is coming 1 (which is incorrect too).

var numofDivs = $("#parentDiv > div").size();
alert(numofDivs);
like image 745
t0mcat Avatar asked May 04 '26 11:05

t0mcat


1 Answers

Hi you should use the function children()

$("#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 what tags to filter, but you can also leave it blank and it will give you all the children

check the API

like image 200
mklfarha Avatar answered May 07 '26 01:05

mklfarha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!