Search code examples
jqueryjquery-selectorsjquery-traversingjquery-filter

What's a better approach to reach to another node that has a common grandparent as the current node?


<tr>
    <th scope="row">
        <span id="home_location_indicator">(Home)</span>
    </th>
    <td>
        <span class="postal_code_display">...</span>
    </td>
    <td><input value="1" name="location_select" type="radio" /></td>
</tr>

Say, I have a <table> that contains a couple <tr>'s like the one above. Among the <tr>'s, there is only one that has <span id="home_location_indicator">(Home)</span>.

I am trying to decide on the approach to take for retrieving the value of the input name="location_select" that belongs to the <tr> containing <span id="home_location_indicator">.

Here are the two approaches I can think of:

  1. $("tr").has("#home_location_indicator").find('input[name="location_select"]').val()
  2. $("#home_location_indicator").parents("tr").find('input[name="location_select"]').val()

Which one is a better approach? And why? Or does it even matter?


Solution

  • The best approach would be to use .closest() instead of .parents(), because it will stop traversing once it finds a match.

    $("#home_location_indicator") // ID, very fast
         .closest("tr") // Upwards traversal, fast, stops at tr
         .find(':radio[name="location_select"]').val() // Find, slow-ish
    

    This is much better than the top-down approach:

    $("tr") // getElementsByTagName, very fast
        .has("#home_location_indicator") // traverse EVERY tr ALL the way down, very slow!
        .find('input[name="location_select"]').val() // Find, slow-ish