Domanda

<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?

È stato utile?

Soluzione

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

Altri suggerimenti

Your second approach is lot better as it would narrow down the traversing starting from ID and traverse from there.. See below with little modification of what you have,

Edit: Using .closest is better than .parents -> Proof

$("#home_location_indicator")
     .closest("tr")
     .find(':radio[name="location_select"]').val()

The .has("#home_location_indicator") in your first approach doesn't make much sense because you are looking for an ID. If you want to get an ID use $('#IDSelector') which is the fastest selector because internally it would use document.getElementByID('IDSelector').

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top