Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery how to use .find

Tags:

jquery

<table id="myTable">
    <tr id="myRow1">
        <td>hi</td>
        <td>hello</td>
        <td>comeon</td>
    </tr>
</table>
  1. In the above scenario, what's the difference between

    $("#myTable").find('tr')

    and

    $("#myTable").find('tr')[0] or $("#myTable").find('tr').get(0)?

  2. Also given $("#myTable").find('tr')[0], how do I get the number of tds under it?

Thanks.

like image 267
Manish Mulani Avatar asked Sep 05 '25 13:09

Manish Mulani


1 Answers

You should not use the [i] or .get(i) syntax unless you really have to, those are ways of accessing the underlying elements within the jQuery object.

The jQuery object is designed to be a wrapper around the elements.

.find() is a jQuery function, it only works on jQuery objects. If you extract the underlying element, it is no longer a jQuery object, just a regular element, so you can not use .find() on it.

If you need the first element only, then use the jQuery filter to get that, leaving the result as a jQuery object. Also, you only really need to use .find() if you are using the part before separately first.

These are the same:

$('#myTable').find('tr:first').find('td');
$('#myTable tr:first td');
like image 155
Orbling Avatar answered Sep 08 '25 11:09

Orbling