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>
Sunil
  • 20,653
  • 28
  • 112
  • 197

1 Answers1

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

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • So the value of `.class1` given for closest means any element with this class that is closest to `firstname`? – Sunil Dec 17 '15 at 22:12
  • 1
    Yes. `closest()` traverses up the DOM to find the nearest parent element which matches the provided selector. In this case, it's looking for a `td` element which is a direct descendant of `.class1`. – Rory McCrossan Dec 17 '15 at 22:14
  • Also, it seems that `.class1 > td` will find all td elements directly under class1 element, but since you mentioned closest to firstname , so we get one of these 2 tds that is closest. – Sunil Dec 17 '15 at 22:18
  • 1
    `Also, it seems that .class1 > td will find all td elements directly under class1 element` No it will only get the single `td` which is the parent of `#firstname` as it's traversing up the DOM tree only. It does not take into account any siblings of parents. – Rory McCrossan Dec 17 '15 at 22:22
  • Ok get it. It always starts from the given element and goes up the DOM tree. – Sunil Dec 17 '15 at 22:26