abdoBim abdoBim - 5 months ago 13
jQuery Question

jQuery: loop through tbody elements and return div elements

I have many tbody elemnts like the one bellow, I try to loop through the tbody elements, then I look for the two div elements in order to give them the largest height of them:

<tbody class="form-row">
<tr class="grp-tr djn-tr form-row has_original">

<td style="" class="original">
<p>
</p>
</td>

<td class="grp-td djn-td">

<div class="grp-readonly">
</div>

</td>

<td class="grp-td djn-td">

<div class="grp-readonly">
</div>

</td>
</tr>
</tbody>


why the function bellow does not find div elements?? and how can I get the two div elements?

function myfunction() {
var elements = $(".form-row");
for (i = 0; i < elements.length - 2; i++) {
alert(elements[i].nodeName); // works well, it shows TBODY
var divs = $(elements[i].find("div.grp-readonly")); // Not working
// some code here
}
}


Thanks.

Answer

$(elements[i].find("div.grp-readonly")); is incorrect, because you must move .find outside of element elector (in other words messing up code).

Try using $.each for simplicity:

function myfunction() {  
  $(".form-row").each(function () {
    var div = $(this).find('.grp-readonly');
    
    console.log(div);
  });
}

myfunction();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody class="form-row">
    <tr class="grp-tr djn-tr form-row has_original">

      <td style="" class="original">
        <p>
        </p>
      </td>

      <td class="grp-td djn-td">

        <div class="grp-readonly">
        </div>

      </td>

      <td class="grp-td djn-td">

        <div class="grp-readonly">
        </div>

      </td>
    </tr>
  </tbody>
</table>