Wednesday, March 23, 2011

JQuery beginner: :has for direct descendants only

Assuming a tree structure like the following: (Ugly legacy layout, sorry)

<tr>                          (1) dont want to select this one  
   <td>
       <table>
           <tr>               (2) not a "special" td, dont select       
               <td.normal>        
           <tr>                (3) this is what I want to select
               <td.special>       
           <tr>
               <td.normal>

I want to select the tr which has a td with class special as direct descendant, i.e. only (2), not (3) [its td is not special], and also not (1) [special td is not a direct descendant but a "grandkid"]

I tried

$("tr:has(td.special)");

but that gives me (1) and (2), because :has means "has somewhere among all my descendants".

What I need is something like :has, but meaning "has among my direct children".

Alternatively, a way to transverse upwards, like "select only the parent of the currently selected element".

Sorry for the simple question, but I can't seem to find it anywhere in the API docs.

From stackoverflow
  • Have you tried $("td.ptextno:contains('Betreuung')").parent() ?

    EDIT: Looks like the question's example changed... try $("td.special").parent()
    EDIT 2: Just so you know, the docs on traversing are here: http://docs.jquery.com/Traversing

    Andrew Hare : +1 $("td.special").parent() is the best way - nice answer.
    Prestaul : @Elmar, you should accept this answer. Just click the check.

0 comments:

Post a Comment