Search code examples
jquerydom-traversal

What's the difference between .closest() and .parents('selector')?


What's the difference between these? Is one more efficient than the other? I'm a little bit confused to why they both exist. Say I have this markup:

<table>
    <tr>
        <td>...</td>
        <td><span class='toggle'>Toggle</span></td>
    </tr>
    <tr>
        <td>...</td>
        <td><span class='toggle'>Toggle</span></td>
    </tr>
    <tr>
        <td>..</td>
        <td><span class='toggle'>Toggle</span></td>
    </tr>
</table>

From the <span> tags I could use either $(this).closest('tr'); or $(this).parents('tr'); to access the parent/closest <tr> tag.


Solution

  • parent returns the immediate parents (one for each element in the caller object) or nothing if the parent does not match the selector. closest returns the closest ancestor matching ancestor for each element (which can be the original element). The third similar function, parents, returns all matching ancestors (not including the element itself).

    Generally, closest is more resistant to refactoring the HTML code than parent, if you choose the selector sensibly.