Selecting Parent Nodes using jQuery

Here’s a quick tip on selecting parent nodes based on something I had to do yesterday with jQuery on a client project.  I have an ASP.NET MVC page that outputs a basic table containing search results and as a user hovers over an item in a map I needed to highlight the appropriate row in the search results by changing its CSS class.  I debated simply adding an ID on the row to make it easy to find but decided I didn’t want to deal with another ID in the DOM.  Here’s what a portion of the view page looks like: 

<tr>
    <td style="width:25%;">
        <span id='restID_<%= rest.RestaurantID %>' desc='<%= addr %>' 
          class="Restaurant" lat='<%= rest.Address.Latitude %>' lon='<%= rest.Address.Longitude %>'>
            <%= rest.Name %>
        </span>
    </td>
    <td style="width:55%;">
        <span><%= addr %></span>                
    </td>
    <td style="width:20%;">
        <%= Html.ActionLink("View Menu","Details","Menu") %>
    </td>
</tr>

On my first attempt I selected the target row the way I typically would do back in the day with plain old JavaScript (I guess we could call it POJ…those that know about POCO and similar terms will understand :-)) which is to select the target span, move up to its parent (the td) and then move up to its parent (the tr).  This works fine, but I ended up going with the following to make it more flexible in case other parents nodes were introduced down the road in the HTML:

function PushPinOver(e)
{
    var shape = $(mapObj)[0].map.GetShapeByID(e.elementID);
    if (shape != null)
    {
        //Find restaurant and highlight it
        current = $('#' + shape.RestaurantID);
        current.parents('tr:eq(0)').addClass('Over');
    }
}

Notice that the last line of code uses the parents() method and says to look for the first tr tag parent (eq(0) filters it down to the first parent).  The code is much more flexible compared to what I originally had especially if I decide to add other tags into the table cells.  As the user hovers off of a map item I then call the following code to locate the same tr parent and remove the CSS class:

function PushPinOut(e)
{
    var shape = $(mapObj)[0].map.GetShapeByID(e.elementID);
    if (shape != null)
    {
        //Find restaurant and highlight it
        if (current != null) current.parents('tr:eq(0)').removeClass('Over');
        current = null;
    }
}

jQuery provides a lot of different options for selecting objects which is why I like it so much….selectors rule!  I’ve cut down my JavaScript coding by at least 50-60% I’d guess as a result of using it.

Update: Another way to do this is to use the closest() method: current.closest(‘tr’)… which is even easier and I like it more for my particular scenario.  Thanks to Raj for commenting about that.

comments powered by Disqus

2 Comments

Comments have been disabled for this content.