1

I have a complex table structure in a web page as given below. There could potentially be deeper nesting of tables.

I am trying to find a jQuery selector to find the closest td to a given input element, with the added constraint that the tr of this td should have a class of 'class1'.

Question: How can I get hold of the single 'td` that I have described in above paragraph with the help of jQuery? I have tried some code but unsuccessfully.

For example, if the given input element is firstname then the td immediately surrounding this element would not be one I am looking for, but the td with a comment saying <!--this is the td I am trying to get--> is the correct td.

I have tried following selector to get this td but its returning 6 td DOM elements, when I was expecting only one. You can see this code in action at this url: demo for this scenario

Code I tried but it doesn't work

$('#firstName').parents("tr.class1").find("td");

Html of nested tables

<table>
   <tr class='class1'>
      <td>
         <!--some content here-->
      </td>
      <td><!--this is the td I am trying to get-->
         <table>
            <tr>
               <td>
                  First Name 
               </td>
               <td>
                  <input type='text' id='firstname'>  
               </td>
            </tr>
            <tr>
               <td>
                  Last Name 
               </td>
               <td>
                  <input type='text' id='lastname'>
               </td>
            </tr>
         </table>
      </td>
   </tr>
</table>
4

1 回答 1

1

To achieve what you require you need to use closest() with the direct child selector, >, to get the parent td. Try this:

var $td = $('#firstname').closest('.class1 > td');

Example fiddle

于 2015-12-17T22:01:37.190 回答